jQuery CSS Class playground

Tags: ,

Today we will play with jQuery CSS class methods such as addClass, removeClass, hasClass and toggleClass and learn some basic implementation to modify the HTML styles on the fly.

Live Demo

jQuery CSS Class Methods:

Lets understand this a small piece of code. First things first, You must include the jQuery library in the <head>...</head>  tag.

Now our page has the jQuery library so lets add some HTML and CSS to play with the jQuery CSS Class methods.

HTML Code:

 

Here we have a DIV tag with ID set to elem and we will use this ID to play with jQuery CSS class methods. Below that we have a paragraph element and four links with different class names. Lets write some CSS code and I will explain the functionality of each link when we add jQuery code.

 CSS Code

 

In the CSS styles, I’ve added some styles to our DIV#elem element and also created a class named hover which will change the background, color and border of the DIV#elem.

Now lets add some jQuery code and learn how these jQuery css methods work.

In the JQuery code, I’ve used the click trigger for all four links we added in the HTML code above. Also I’ve used return false;  so when we click on the link it should not redirect the user to any page or use # in the current page url. Also I’ve added another line of code to modify the HTML of the #elem element when we click on these links. Don’t get confused with the .html() method, this is not required, I just added it to explain the functionality.

The first link with class .add-class will add the .hover class to the #elem element. If you want to add multiple classes with one trigger you can specify different class names separated with a space as we normally do in normal HTML code. Once we click on this link, .hover class will be added to the #elem HTML element and the inner HTML will be changed and show us the result. You can click on the addClass link above and see it in action.

The second link with class .remove-class will remove the .hover class from the #elem element. If the element doesn’t have .hover class, it won’t do anything so remove class will be used only to remove any applied class.

The third link with class .toggleClass will toggle the .hove class on #elem element. If the element does not has .hover class it will add the same otherwise vice versa. In this code, I’ve used the jQuery css method hasClass to check if the element has the .hover class or not. and the content of the #elem element is changed accordingly.

The fourth link will only check if the class .hover is applied to the #elem element or not and change the HTML code of the #elem element accordingly.

I hope this will clarify any doubts on using these methods, in case you have any questions or suggestions, please use the comments below to start conversation on this topic.

Leave a Comment

Your email address will not be published.*

*