Mostafa Talebi
Mostafa Talebi

Reputation: 9183

Using jquery options with $.fn causes errors

In a part in my plugin (jquery) i add CSS rules to an element. Here is the code:

tagSet.eq(index).css({
                    options.tag_direction : (xy[0]+"px "+strictCSS),
                    "position" : ("relative"+" "+strictCSS),

                    "top" : (xy[1]+"px "+strictCSS),
                })

But, if I replace the "left" with options.get_direction_hor it erros. Here is the error:

SyntaxError: missing : after property id


options.tag_direction_hor : (xy[0]+"px "+strictCSS),

I do this because I want the user (developer) be able to use the plugin with "left" or "right" css rule so to avoid hacking the source code.

I also have got a console.log(options.get_direction_hor) and it outputted correctly. Is there anything about javascript objects that I'm missing here?

Here is the options signature:

$.fn.mtTagger = function(options){
        var options = $.extend({
            tag_class : ".mtTagElement", //
            tag_before_callback : null,  // a callback to gets fired when the pages(or section) loads       
            tag_htmlTag : "span", // HTML elements to be selected as children           
            tag_limit_to_class : false, // if true, then the selection is $(element.class) than it was $(element) if false
            tag_mouse_in_callback : null, // a callback to gets fired when the mouse moves enters
            tag_mouse_out_callback : null, // a callback to gets fired when the mouse moves leaves
            tag_strict_css : false, // if true, then !important will be appened to the end of each CSS rule
            tag_direction_hor : null
        }, options)

Upvotes: 1

Views: 41

Answers (1)

dfsq
dfsq

Reputation: 193261

Your syntax is not correct. Object literal definition cannot contain dynamic keys like you are trying to provide options.tag_direction. Instead you can split it in two parts:

var styles = {
    position: "relative" + " " + strictCSS,
    top: xy[1] + "px " + strictCSS
};
styles[options.tag_direction] = xy[0] + "px " + strictCSS;
tagSet.eq(index).css(styles);

Also remember to clean up trailing comma after the last object property (will break in old IE's).

Upvotes: 2

Related Questions