Home arrow JavaScript arrow More Dynamic jQuery Styling Techniques
JAVASCRIPT

More Dynamic jQuery Styling Techniques


Being a Javascript framework, jQuery is great at performing all sorts of clever DOM manipulations, handling AJAX requests, processing web page events and so forth. Blessed with such remarkable features, it seems pointless to use the library for more banal things, like assigning and removing styles from one or more HTML elements. But this is a misleading concept. In this article, I will show you why.

Author Info:
By: Alejandro Gervasio
Rating: 5 stars5 stars5 stars5 stars5 stars / 3
September 07, 2011

print this article
SEARCH DEVARTICLES

Being a Javascript framework, jQuery is great at performing all sorts of clever DOM manipulations, handling AJAX requests, processing web page events and so forth. Blessed with such remarkable features, it seems pointless to use the library for more banal things, like assigning and removing styles from one or more HTML elements. But this is a misleading concept. In this article, I will show you why.

The library packages a set of convenient methods that permit you to manipulate the styles of several web page elements in a few simple steps. In the introductory part of this tutorial I took an in-depth look at the library’s “css()” method, which allows you to attach one or more CSS properties to a given selector.

If you want to read more about this, you can find the article here: http://www.devarticles.com/c/a/JavaScript/Dynamic-jQuery-Styling/

It’s worth noting that “css()” isn’t the only method jQuery offers for dynamically styling web page elements, as the library also provides “addClass()”, “removeClass()” and “hasClass()”, which can be used for manipulating entire CSS classes.

In this final part I’ll be developing some approachable examples that will show you how to work with the methods in question, so that you can start using them for enhancing the behavior of your own web pages.

Making the First Move: Defining a Sample (X)HTML Document

The first jQuery method I plan to discuss here is “addClass()”. As its name clearly suggests, this method allows you to attach a specified CSS class to one or more HTML elements.

The best manner to demonstrate the functionality of “addClass()” is by example; in keeping with this idea, below I coded a basic web page, which defines a class called “clicked”. As you’ll see in a moment, I’ll be using the corresponding method for adding this class to a couple of divs. 

For the moment, however, pay attention to this sample web page, which looks like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Example using the 'addClass()' method</title>
<style type="text/css">
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;
}
/* class to be assigned to the target divs */
.clicked {
    background-color: #ffffc0;
    border: 2px solid red;
}
</style>
</head>
<body>
<div id="wrapper">
    <div id="header">
        <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="main">
        <h2>Example using the 'addClass()' method</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="footer">
        <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 structure of the above web page is anything but complex. As you can see, it includes within its “main” section a pair of divs which contain some sample paragraphs. In addition, the page defines the aforementioned “clicked” CSS class, which is the one that I plan to attach to the divs via the “addClass()” method.

Of course, this can be done directly with CSS, but what if you want to do that when clicking on the target elements? Here’s exactly where the functionality of “addClass()” really shines, as the method permits you to accomplish this in a snap.

In the coming section I’ll be demonstrating how easy it is to tie the previous “clicked” CSS class to the divs we just defined.

Assigning a CSS Class to an HTML Element: Introducing the “addClass()” Method

There are countless times where it’s necessary to attach a CSS class to a specific HTML element in response to a mouse click or other event. In a case like this, the “addClass()” method makes this process a no-brainer.

In line with this concept, I added a short snippet to the web page defined previously, which appends the sample “clicked” class to the sample divs. Take a look at it:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Example using the 'addClass()' method</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    // assign the 'clicked' class to the target divs when clicking on them
    $("#main div").click(function() {
        $(this).addClass('clicked');
    });
});
</script>
<style type="text/css">
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;
}
/* class to be assigned to the target divs */
.clicked {
    background-color: #ffffc0;
    border: 2px solid red;
}
</style>
</head>
<body>
<div id="wrapper">
    <div id="header">
        <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="main">
        <h2>Example using the 'addClass()' method</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="footer">
        <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 shown above, using the “addClass()” method is indeed a breeze. In this particular case, the method has been employed for altering the visual presentation of some generic containers when they are clicked upon; it’s possible, however, to utilize it with other events and get an identical result as well.

Here’s the one generated by the earlier web page when the “clicked” class is added to the target divs:

There you have it. Even though the logic behind “addClass()” is really easy to follow, you should keep in mind that the method does exactly what its name implies: it adds a class to one or multiple elements, merging the new class with the ones that might have been assigned previously (in other words it won’t remove the existing classes).

You may come to a point where you’ll need to remove a class in response to a certain event. In such a case, jQuery provides the complementary “removeClass()” method, which performs this task in a straightforward fashion.

Again, the most effective means of understanding the inner workings of “removeClass()” is by example. Therefore, in the coming segment I’ll be modifying the one that you just saw, which this time will use the mentioned method for switching the styles assigned to the sample divs.

Making Things a Bit More Functional: Using the “hasClass()” and “removeClass()” Methods

If you’re interested in seeing how to use the “removeClass()” method mentioned in the preceding segment, then pay attention to the following example, which will hopefully be quite instructive. Simply put, all it does is alternately attach/detach from the target divs the already familiar “clicked” CSS class when they are clicked upon.

Here’s how this improved example looks:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Example using the 'addClass()', 'hasClass()' and 'removeClass()' methods</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    // assign the 'clicked' class to the target divs when clicking on them
    $("#main div").click(function() {
        if (!$(this).hasClass('clicked')) {
            $(this).addClass('clicked');
        }
        else {
            $(this).removeClass('clicked');
        }
    });
});
</script>
<style type="text/css">
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;
}
/* class to be assigned to the target divs */
.clicked {
    background-color: #ffffC0;
    border: 2px solid red;
}
</style>
</head>
<body>
<div id="wrapper">
    <div id="header">
        <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="main">
        <h2>Example using the 'addClass()', 'hasClass()' and 'removeClass()' methods</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="footer">
        <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>

Even though the above example is admittedly pretty naive, it comes in handy for showing how to use the “addClass()”, “removeClass()” and “hasClass()” methods in the same script . In this case, the latter is used for determining if the element that was clicked has the “clicked” CSS class attached to it. If this condition is false, then the class is assigned to it; otherwise, it’s simply removed from the element via the “removeClass()” method.   

Now, if you try out the previous web page on your own browser, the target elements should look similar to this when clicking on them:

Logically, there’re literally hundreds of different situations where you’ll need to utilize the earlier methods in a more realistic fashion. Nonetheless, the set of examples shown in this tutorial should give you a clearer idea on how to use the functionality offered by jQuery for manipulating dynamically the styles of web page elements. So, go ahead and start using these methods in all kind of useful and imaginative ways!  

Final Thoughts

In the course of this two-part tutorial, I provided you with a quick introduction to styling dynamically HTML elements with jQuery. As you saw for yourself, either if you need to assign individual properties to one or more selectors, or attach/remove full CSS classes from them, the library has a method that will neatly fit your requirements.

Moreover, in the earlier examples, I showed you how to use the “css()”, “addClass()”, “removeClass()” and “hasClass()” methods in a few trivial and somewhat contrived use cases. Don’t let the simplicity of them fool you, as when used in more complex and creative manners, they can be powerful allied that will let you perform all sort of style manipulations on the elements of your web-based user interfaces. So, keep them always at hand in your toolbox. You won’t regret at all, trust me.

See you in the next web design tutorial!


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