Home arrow JavaScript arrow Dynamic jQuery Styling
JAVASCRIPT

Dynamic jQuery Styling


In this jQuery programming tutorial, you will learn how to dynamically style with jQuery and the "css()" method.

Author Info:
By: Alejandro Gervasio
Rating: 5 stars5 stars5 stars5 stars5 stars / 11
August 19, 2011

print this article
SEARCH DEVARTICLES

In this jQuery programming tutorial, you will learn how to dynamically style with jQuery and the "css()" method.

The popularity jQuery has gained in the last few years is for a simple reason: based on the functionality provided by a bunch of intuitive methods, the library allows for the execution of complex tasks, including all sorts of clever DOM traversal/manipulations, AJAX-based processing and the implementation of engaging animation effects (among others).

When analyzed from that standpoint, it seems overkill to use the library for doing common and trivial things, such as dynamically assigning styles to one or multiple HTML elements, right? After all, that’s why CSS was created in the first place! Moreover, the concept sounds like a confusing mix of visual presentation and behavior that should be discarded in favor of more efficient and well-differentiated approaches.

However, there’s plenty of use cases in the real world where the manipulation of CSS styles with jQuery can be really useful. And apparently, the library’s developers feel the same, as they included a set of handy methods that allow you to do this in a straightforward fashion.

Even if you’re just learning jQuery, you’ll probably know that it packages the “css()”, “addClass()/removeClass()” and “hasClass()” methods, which permit you to manipulate individual styles and entire CSS classes with minor hassle. Given that, and assuming that you’re interested in learning how to work with the above mentioned methods, in this two-part article series I’ll be taking an in-depth look at them, starting with the simple - yet powerful - “css()” method.

Getting Started: Building a Sample Web Page

Before I start showing you all the smart things you can do with the “css()” method, it’s necessary to create a sample web page that can be used for testing purposes. Below I defined a basic (X)HTML document, whose structure looks as follows:

<!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Strict//EN&quot; &quot;<a href="http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd</a>&quot;>

<html xmlns=&quot;<a href="http://www.w3.org/1999/xhtml">http://www.w3.org/1999/xhtml</a>&quot;>

<head>

<meta http-equiv=&quot;Content-Type&quotcontent=&quot;text/htmlcharset=utf-8&quot; />

<title>Example using the 'css()' method with a single property</title>

<style type=&quot;text/css&quot;>

body 
{

    padding
0;

    margin
0;

    background
#eee;

    
font0.8em ArialHelveticasans-serif;

    color
#000;

}

h2 
{

    padding
-bottom10px;

    margin
0 0 30px 0;

    font
-size3em;

    color
#585858;

}

/* main wrapper */

#wrapper {

    
width650px;

    margin
0 auto;

    background
#fff;

}

/* main sections */

#header, #main, #footer {

    
padding20px;

}

#main div {

    
padding20px;

    margin
-bottom20px;

    background
-color#c0ffff;

}

</style>

</head>

<body>

<div id=&quot;wrapper&quot;>

    
<div id=&quot;header&quot;>

        
<h2>Header section</h2>

        
<p>Lorem ipsum dolor sit ametconsectetur adipiscing elitSuspendisse auctor commodo risuset ultrices sapien vestibulum nonMaecenas scelerisque quam a nulla mattis tinciduntEtiam massa liberopharetra vel laoreet etultrices non leoLorem ipsum dolor sit ametconsectetur adipiscing elitSed posuere ullamcorper lacus et sollicitudinMorbi ultrices condimentum lacussit amet venenatis purus bibendum sit amet.</p>

    
</div>

    
<div id=&quot;main&quot;>

        
<h2>Example using the 'css()' method with a single property</h2>

        
<div>

            
<p>Lorem ipsum dolor sit ametconsectetur adipiscing elitSuspendisse auctor commodo risuset ultrices sapien vestibulum nonMaecenas scelerisque quam a nulla mattis tinciduntEtiam massa liberopharetra vel laoreet etultrices non leoLorem ipsum dolor sit ametconsectetur adipiscing elitSed posuere ullamcorper lacus et sollicitudinMorbi ultrices condimentum lacussit amet venenatis purus bibendum sit amet.</p>

        
</div>

        
<div>

            
<p>Lorem ipsum dolor sit ametconsectetur adipiscing elitSuspendisse auctor commodo risuset ultrices sapien vestibulum nonMaecenas scelerisque quam a nulla mattis tinciduntEtiam massa liberopharetra vel laoreet etultrices non leoLorem ipsum dolor sit ametconsectetur adipiscing elitSed posuere ullamcorper lacus et sollicitudinMorbi ultrices condimentum lacussit amet venenatis purus bibendum sit amet.</p>

        
</div>

    
</div>

    
<div id=&quot;footer&quot;>

        
<h2>Footer section</h2>

        
<p>Lorem ipsum dolor sit ametconsectetur adipiscing elitSuspendisse auctor commodo risuset ultrices sapien vestibulum nonMaecenas scelerisque quam a nulla mattis tinciduntEtiam massa liberopharetra vel laoreet etultrices non leoLorem ipsum dolor sit ametconsectetur adipiscing elitSed posuere ullamcorper lacus et sollicitudinMorbi ultrices condimentum lacussit amet venenatis purus bibendum sit amet.</p>

    
</div>

</div>

</body>

</html>

The above page is somewhat primitive, as it only defines a few wrapping areas and nothing else. Nevertheless, you should pay attention to the couple of divs included within the “main” section: as you can see, they’ve been assigned some basic styles via CSS, including some padding, a bottom margin and a background color as well.

So far this is pretty standard and boring. However, imagine for a moment that you need to change the appearance of the previous divs when they are clicked on. For obvious reasons, this can’t be done with plain CSS, so here’s exactly where the “css()” jQuery method comes into play, as it permits us to achieve this task in a truly simple manner.

In the following segment I’ll be using the functionality of “css()” to dynamically assign a different background color to the target divs.    

Making Things More Dynamic: Introducing the “css()” Method

Being a solid wrapper around the native “style” JavaScript object, the “css()” method is undeniably the workhorse of jQuery when it comes to styling HTML elements in a dynamic way.

It’s quite possibl that you’re familiar with the method’s inner workings already, however, if you’re starting to explore the library’s API and still don’t know how to use it, be sure to check out the following example, which takes advantage of “css()” for changing the background color of the two sample divs defined before.

Here’s how this example looks:  

<!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Strict//EN&quot; &quot;<a href="http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd</a>&quot;>

<html xmlns=&quot;<a href="http://www.w3.org/1999/xhtml">http://www.w3.org/1999/xhtml</a>&quot;>

<head>

<meta http-equiv=&quot;Content-Type&quotcontent=&quot;text/htmlcharset=utf-8&quot; />

<title>Example using the 'css()' method with a single property</title>

<script type=&quot;text/javascript&quotsrc=&quot;<a href="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js">https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js&quot;></script</a>>

<script type=&quot;text/javascript&quot;>

$(document).ready(function() {

    
// change the style of the target divs when clicking on them

    
$(&quot;#main div&quot;).click(function() {

        
$(this).css('background-color''#ffffC0');

    
});

});

</script>


<style type=&quot;text/css&quot;>

body {

    padding: 0;

    margin: 0;

    background: #eee;

    font: 0.8em Arial, Helvetica, sans-serif;

    color: #000;

}

h2 {

    padding-bottom: 10px;

    margin: 0 0 30px 0;

    font-size: 3em;

    color: #585858;

}

/* main wrapper */

#wrapper {

    width: 650px;

    margin: 0 auto;

    background: #fff;

}

/* main sections */

#header, #main, #footer {

    padding: 20px;

}

#main div {

    padding: 20px;

    margin-bottom: 20px;

    background-color: #c0ffff;

}

</style>

</head>

<body>

<div id=&quot;wrapper&quot;>

    <div id=&quot;header&quot;>

        <h2>Header section</h2>

        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet.</p>

    </div>

    <div id=&quot;main&quot;>

        <h2>Example using the 'css()' method with a single property</h2>

        <div>

            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet.</p>

        </div>

        <div>

            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet.</p>

        </div>

    </div>

    <div id=&quot;footer&quot;>

        <h2>Footer section</h2>

        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet.</p>

    </div>

</div>

</body>

</html>

The logic of the above code sample should be really easy to follow. As you can see, in this case the argument passed to the “css()” method is only the “background-color” property, along with the corresponding color value. Moreover, the method is called when clicking on the target divs, but logically it’s possible to invoke it in response to other event(s) and get an identical result as well.

And speaking of results, here’s the one produced by the above example:

With a simple method call, it’s possible to assign a new property to one or several HTML elements. However, the functionality of the “css()” method doesn’t stop there, as it can be used for assigning multiple properties in one go. If you’re wondering how to accomplish this, in the coming segment I’ll be amending the previous example to utilize the method for adding a new the background color and give a red border to the target divs.

Digging Deeper Into the “css()” Method: Assigning Multiple Properties to an HTML Element

One of the most appealing facets of the “css()” method is its ability to assign multiple properties to a given web page element in one go. To elaborate this concept, I included an example similar to the one that you saw in the preceding segment, which now uses the method for decorating the target divs with a different background color and a 2px border. Check it out:

<!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Strict//EN&quot; &quot;<a href="http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd</a>&quot;>

<html xmlns=&quot;<a href="http://www.w3.org/1999/xhtml">http://www.w3.org/1999/xhtml</a>&quot;>

<head>

<meta http-equiv=&quot;Content-Type&quotcontent=&quot;text/htmlcharset=utf-8&quot; />

<title>Example using the 'css()' method with multiple properties</title>

<script type=&quot;text/javascript&quotsrc=&quot;<a href="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js">https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js&quot;></script</a>>

<script type=&quot;text/javascript&quot;>

$(document).ready(function() {

    
// change the style of the target divs when clicking on them

    
$(&quot;#main div&quot;).click(function() {

        
$(this).css({'background-color''#ffffC0''border''2px solid red'});

    
});

});

</script>


<style type=&quot;text/css&quot;>

body {

    padding: 0;

    margin: 0;

    background: #eee;

    font: 0.8em Arial, Helvetica, sans-serif;

    color: #000;

}

h2 {

    padding-bottom: 10px;

    margin: 0 0 30px 0;

    font-size: 3em;

    color: #585858;

}

/* main wrapper */

#wrapper {

    width: 650px;

    margin: 0 auto;

    background: #fff;

}

/* main sections */

#header, #main, #footer {

    padding: 20px;

}

#main div {

    padding: 20px;

    margin-bottom: 20px;

    background-color: #c0ffff;

}

</style>

</head>

<body>

<div id=&quot;wrapper&quot;>

    <div id=&quot;header&quot;>

        <h2>Header section</h2>

        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet.</p>

    </div>

    <div id=&quot;main&quot;>

        <h2>Example using the 'css()' method with multiple properties</h2>

        <div>

            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet.</p>

        </div>

        <div>

            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet.</p>

        </div>

    </div>

    <div id=&quot;footer&quot;>

        <h2>Footer section</h2>

        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet.</p>

    </div>

</div>

</body>

</html>

As the above code shows, it’s really simple to call the “css()” method with a JSON object containing a set of properties that will be applied to one or several HTML elements. In this particular case, the properties passed to the method are only two, namely “background-color” and “border”. It’s possible, though, to pass many others, as long as you stick with the JSON notation.

And finally, here’s how the earlier divs look when they are clicked on:

Understanding the logic behind the “css()” method should be a simple process that can be mastered with minor hassle. So, armed with the set of examples coded above, you should be able to create your own examples and put the method to work for you in no time.

Of course, jQuery includes a few other handy methods that can be used for dynamically manipulating the CSS styles of web page elements; these will be covered in depth in the final part of this tutorial.

Final Thoughts

In this first part of this two-part tutorial, I went through the development of a few easy-to-follow examples, which showed how easy it is to dynamically style multiple HTML elements with the “css()” method provided by jQuery. Even when the mentioned examples were a little bit contrived, they (hopefully) came in handy for demonstrating that the method permits you to assign one or several CSS properties on the fly with extreme ease.

As I said before, “css()” isn’t the only trooper that jQuery offers when it comes to styling web page elements, as the library includes the complementary “hasClass()”, “addClass()” and “removeClass()” methods as well. The former can be used for checking if a selector contains a specified class, and the last two for assigning a class to the selector in question.

Taking into account that you might be interested in learning the basics of these methods, in the final installment I’ll be providing you with some additional examples, which will teach you how to utilize them in a few concrete use cases.

Don’t miss the last part!


DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

All JavaScript Tutorials
More By Alejandro Gervasio


blog comments powered by Disqus
JAVASCRIPT ARTICLES

- Project Nashorn to Make Java, JavaScript Wor...
- JavaScript Virus Attacks Tumblr Blogs
- Google Releases Stable Dart Version, JavaScr...
- Khan Academy Unveils New JavaScript Learning...
- Accessing Nitro? There`s an App for That
- JQuery 2.0 Leaving Older IE Versions Behind
- Fastest JavaScript Engine Might Surprise You
- Microsoft Adjusting Chakra for IE 10
- Brendan Eich: We Don`t Need Google Native Cl...
- An Overview of JavaScript Statements
- An Overview of JavaScript Operators
- Overview of JavaScript Variables
- More of the Top jQuery Social Plugins
- The Top jQuery Social Plugins
- More of the Top jQuery Slider Plugins

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials