jQuery Fundamentals–Part 2- Dynamically Adding CSS Classes

Down Arrow

Adding CSS classes to jQuery is one of the most commonly performed tasks and is an extremely powerful tool in the web designers toolbox. Anything that you can do with CSS you can do dynamically and jQuery even offers you some additional effects which can add that extra layer of gloss to your website. Here is a simple example to illustrate the concept. In this example, imagine I have made a design choice to make all the links on my page the colour Teal and the font Tahoma. I might construct a CSS class like this:

.teallink {color:Teal;font-family:Tahoma;}

The body of my page containing a link might look like this:

<body> <a id="mylink" href="http://www.perceptiveflow.com">Web Design</a> <a id="mysecondlink" href="http://www.perceptiveflow.com">SEO</a> </body> 

If I load my page now, the output I get is as follow:
image

Adding the CSS Class

To apply my ‘teallink’ CSS class to the links on my page I just need to use the following syntax:

    <script type="text/javascript"> $(document).ready(function () {
$("a").addClass("teallink");
});
</script>

(Note: For details of the ‘ready’ event – See jQuery Fundamentals – Part1)

The resulting page refresh gives me the result I am after:

image

Adding a CSS Class to a single HTML element

As shown in part 1, you can apply jQuery to a single element using the #id syntax. For example, if I just wanted to apply the teal style to the first link then I could use the following syntax:

    <script type="text/javascript"> $(document).ready(function () {
$("#mylink").addClass("teallink");
});
</script>

image

Removing a CSS Class from an element

If we want to remove CSS classes from our HTML elements then this is just as simple:

    <script type="text/javascript"> $(document).ready(function () {
$("#mylink").removeClass("teallink");
});
</script>


And that concludes this tutorial. More no nonsense to follow. Below is the entire code for convenience.

<html> <head> <title>jQuery - Adding CSS Classes</title> <script type="text/javascript" src="Scripts/jquery.js"></script> <style type="text/css"> .teallink {color:Teal;font-family:Tahoma;}
</style> <script type="text/javascript"> $(document).ready(function () {
$("#mylink").addClass("teallink");
});
</script> </head> <body> <a id="mylink" href="http://www.perceptiveflow.com">Web Design</a> <a id="mysecondlink" href="http://www.perceptiveflow.com">SEO</a> </body> </html>

Mark

SHARE
comments powered by Disqus

Get in touch today!

Start your project