A Faster More Flexible Way to Write jQuery CSS

In most instances its always better to keep your styles inside a style sheet. There are times however, when you need JavaScript to set or animate some styles.

In just such an instance, we find ourselves sometimes writing things like this:

The Problem:

$('#someElm').css({
	width:'100px',
	height:'100px',
	left:'100px',
	top:'100px',
	lineHeight:'100px'
});

There really is no problem with this script, the issue that stands out is that we are repeating “100px” five times over. If you are like me, you also wonder if there is a way to sum up these repeated values. Well, as matter of fact there is a way to cut down on repeated CSS values.

The Solution:

var css = {};
css.width = css.height = css.top = css.left = css.lineHeight = '100px';
$('#someElm').css(css);

COOL! We just summed up three style rule’s values into a single call!

We did this by first instating a empty object called css (var css= {};), then we assigned our style rules and values to this object (css.* = ‘100px’) using the dot notation. Keep in mind, that css keywords like lineHeight or zIndex translate into line-height or z-index once written inline by jQuery, so be mindful of your camel case.

A Step Further

Being able to sum up our styles values into a single call is very helpful indeed, but that’s not all we can now do with this method folks. With this approach, you have set the platform for a whole new level at making this single calls more dynamic if you will.

Lets say that we want to have a condition on the values our elements style receives. We can do so more efficiently now that we have installed an object.

Lets have a look see:

var css = {};
var start = false;
css.width = css.height = css.top = css.left = css.lineHeight = (start == false) ? '100px' : '50px'; 
$('#someElm').css(css);

WOW, now that’s some sweet stuff!

Instead of writing essentially two different calls to “$(‘#someElm’)” thats nested in a long if/else condition, we can still sum up our css value and make use of Javascript Ternary Operator.

So to recap, we can install an empty object and toss our styles and repeated values into and assign the styles to elements. We can also make use of Javascript Ternary Operator to better assist us in summing up our repeated values dynamically.

Thanks!

Devin R. Olsen

Located in Portland Oregon. I like to teach, share and dabble deep into the digital dark arts of web and game development.

More Posts

Follow Me:
TwitterFacebookGoogle Plus