tags:

views:

81

answers:

1

I saw this in our codebase the other day:

            link.attr('style', map({
                color: '#9a4d9e',
                cursor: 'default'
            }));

map is defined as:

function map(map) {
    var cssValue = [];

    for (var o in map) {
        cssValue.push(o + ':' + map[o] + ';')
    }

    return cssValue.join(';');
}

Is map necessarily? Is there a shorter way to do this?

It's important to note that the "style" attribute overrides any styles set by a class added/defined in the "class" attribute.

+5  A: 

Probably not. A better solution may be to use CSS:

link.css({color: '#9a4d9e',
          cursor: 'default'});

However, .attr('style',) also removes the previous inline style, so it doesn't behave exactly the same.
If you are going to use attr, it's input should be a string, not an object, it isn't specialized to work with the style attribute. an alternative in that case is:

link.attr('style', "color:'#9a4d9e';cursor:'default'");

Seems cleaner in this case. In other cases, your map makes it easier to insert variables into the CSS.
map could have been named better though. It also has an implementation error - it adds double semicolons between attributes: color:red;;cursor:default;

A simple solution to remove the previews style is to call .removeAttr('style') before calling css.

Kobi
If you want to clear the style first, go with `link.attr('css','').css( ... );`
josh3736
@josh - Thanks, I probably should have mentioned that. That'd be `link.removeAttr('style')` though.
Kobi
+1 Though I don't really see the point of the map over using the raw CSS string. It might win you a (very, very) small amount of syntatic checking.
CurtainDog
@CurtainDog - I agree. On another thought, I changed "it depends" to "probably not" - two steps down on my hesitation scale.
Kobi