I love the way jQuery has integrated CSS styling into their library, it’s so simple! And JavaScript objects have very similar notation to CSS itself so that makes it all the more intuitive. E.g.

var cssChoices = {
    // Looks like CSS!
    color: 'blue',
    width: '200px',
    border: '1px solid green'
};
$('#elem').css(cssChoices);

The problem arises when you need to have access to the selected element(s). One common way of achieving this is through the each() iterator which gives us access to each individual element, e.g.

$('a').each(function(){
    var singleLink = $(this);
});

This becomes a bit cumbersome though and looks quite bloated to the non-jQuery folk. What would be great is if we could pass a function to the CSS method; this function would have access to each individual element. I’ve created a plugin which does exactly that!

The Code

// Allows you to pass a function to jQuery's 'css' method
// This means you can use the -this- keyword to reference
// the current element!!!
(function($){
    $.fn.oldCSSMethod = $.fn.css;
    $.fn.css = function(o) {
        return $.isFunction(o) ? 
            $(this).each(function(){
                $(this).oldCSSMethod(o.call(this));
            })
            : $(this).oldCSSMethod.apply($(this), arguments);
    }
})(jQuery);

Usage:

The function which is passed as a parameter MUST return an object: E.g.

// Invert colors of all links:
$('a').css(function(){
 
    var thisColor = $(this).css('color'),
        thisBGColor = $(this).css('backgroundColor');
 
    return {
        color: thisBGColor,
        backgroundColor: thisColor
    }
 
});

Smashing! 🙂

Thanks for reading! Please share your thoughts with me on Twitter. Have a great day!