Dynamically Changing CSS Using jQuery

We use alot of jQuery around the eleven2 site, to make the user experience even greater. For instance, on our cloud hosting page, the entire slider is jQuery based. Button hover effects are slightly faded using jQuery, and of course our beautiful jQuery lightbox that we use.

I’m going to share with you today a very simple trick to get jQuery to perform simple CSS changes. This comes in handy with alot of the jQuery snippets I write. Lets start with the basics shall we…

Changing Colours & Backgrounds

//Changing a paragraphs text colour to red

//Changing div class bg to orange

So that’s some basic jQuery functionality we just covered. So now lets move on and add in some jQuery changes when your mouse hovers on/off…

Mouseover Hide / Show

        //Mouseover hides the box
        function() { $(this).css({"display":"none"});
        //Mouse off then reveals the box
    	function() { $(this).css({"display":"block"});

Increasing Div Width on Click

Now lets make a snippet so that when a link is clicked, a certain div expands in width.

$('a.myclass').click( function() {

Adding to Existing CSS Values

For instance, if a div has margin-left as 50px, we can then add 20px to this using a simple jQuery function, resulting in the margin-left property to be 70px.

//Increase divs margin left by 20px
$('.mydiv').css( "margin-left", "+=20" );

Taking it Further…

Have a play around with some of the snippets above. You can incorporate them with other jQuery snippets too, and if you want to go really advanced, you can add in some animation effects etc. Feel free to comment with any questions you have.