jQuery addClass: 13 Ways to Use In Different Scenarios
jQuery addclass() method is used to add one or more classes to a selected element.
I think you already know what jQuery .addClass() does, so why don’t we cut to the chase and show you the 13 ways to use addClass() in different scenarios.
If you don’t know what jQuery .addClass() does, click here.
Basic Syntax:
$(selector).addClass('one or more class names');
Example # 1: Add class to a selected paragraph, but remove if another paragraph is selected
Let’s say; you have three paragraph elements, and you want to highlight selected paragraph on click.
HTML
<p class="select1">First Paragraph</p> <p class="select2">Second Paragraph</p> <p class="select3">Third Paragraph</p>
CSS
.selected { background-color: #000000; color: #ffffff; }
jQuery
$(document).ready(function() { $('p').on('click', function() { $('p').removeClass('selected'); $(this).addClass('selected'); }); });
Demo: http://jsfiddle.net/cd9g72vw/
- .on(): We used this method to trigger the click event handler.
- .removeClass(): To remove the class “selected” from other not selected paragraphs.
- $(this): To add the class “selected” on the clicked “p” element.
Example # 2: Animation with .addClass() and CSS3
We are going to accomplish this with the help of CSS3. Let’s see this in action:
HTML
<div id="animation" class="limegreen"></div>
CSS
#animation{ -webkit-transition: all 0.5s ease; -moz-transition: all 0.5s ease; -o-transition: all 0.5s ease; transition: all 0.5s ease; } .limegreen{ background-color: #32CD32; width: 150px; height: 150px; } .lightblue{ background-color: #ADD8E6; width: 200px; height: 200px; }
jQuery
$(document).ready(function() { $('#animation').hover(function() { $(this).addClass('lightblue'); }, function() { $(this).removeClass('lightblue'); }); });
The above example is not tested on internet explorer.
Demo: http://jsfiddle.net/w94aLtq6/
Overview
We used CSS3 transitions for the effects and jQuery’s .addClass() for changing the class name on “hover” in the above example.
Example # 3: Add a class on scrolling with jQuery and jQuery UI
With the help of jQuery and jQuery UI, add animation on scrolling down to 100px.
HTML
<p>This is example text</p> <p>This is example text</p> <p>This is example text</p> <p>This is example text</p> <p>This is example text</p> <p>This is example text</p> <p>This is example text</p> <div class="nav">This is a test .nav element</div> <p>This is example text</p> <p>This is example text</p> <p>This is example text</p> <p>This is example text</p> <p>This is example text</p> <p>This is example text</p> <p>This is example text</p> <p>This is example text</p> <p>This is example text</p> <p>This is example text</p> <p>This is example text</p>
CSS
.addnewclass { color: white; background-color: #000000; }
jQuery
$(window).scroll(function() { var scroll = $(window).scrollTop(); if (scroll >= 100) { setTimeout(function() { $(".nav").addClass("addnewclass", 1000); }, 500); } });
Demo: http://jsfiddle.net/sfufnp0h/
Overview
Don’t forget to include jQuery UI library inside the <head> section of the HTML document.
- $(window).scroll() method is used to trigger the scroll event when window is ready.
- .scrollTop() is used to get the current vertical position.
- if (scroll >= 100) means, execute the code below if scrolling reached to 100px.
- setTimeout() is used to execute the code after a specified time, in our case 500 milliseconds.
Example # 4: Add class when there is specific text found inside a div
Let’s say, you have a div with a lot of elements and text, and you want to apply different styling to the div having a specific text. For this try our example down below:
HTML
<p>This is example text</p> <div id="textfound"> <p>Text Found</p> <h1>Text Found</h1> </div>
CSS
.addaclass { color: white; background-color: #add8e6; font-size:16px; }
jQuery
$(document).ready(function() { var textToFind = "Text Found"; if ($("#textfound:contains('" + textToFind + "')")) { $('#textfound').addClass('addaclass'); } });
Demo: http://jsfiddle.net/2ouy4rtn/
Working
- Assigned the phrase “Text Found” to a variable “textToFind”.
- Searched the string inside a div “textfound”.
- If found, added the class “addaclass” to the div.
Example # 5: Change background color by adding a class on mouseover
In this example, we are changing the background of a paragraph on .mouseover().
HTML
<p id="changebg" class="bg1">This is example text</p>
CSS
.bg1 { background-color:#0C9; width: 150px; height: 150px; } .bg2 { background-color: #30F; width: 150px; height: 150px; }
jQuery
$(document).ready(function() { $('#changebg').mouseover(function() { $(this).addClass('bg2'); $(this).removeClass('bg1'); }); $('#changebg').mouseout(function() { $(this).addClass('bg1'); $(this).removeClass('bg2'); }); });
Demo: http://jsfiddle.net/f4qeskc9/
Example # 6: Add and remove a class after a delay
In this example, we are going to add and remove a class after a delay. The jQuery methods used in this example are: addClass(), delay(), dequeue() and removeClass().
HTML
<h1 id="delay">Sample Text</h1>
CSS
.classadded { background-color:#0C9; width: 500px; height: 150px; }
jQuery
$(document).ready(function() { $("#delay").addClass("classadded").delay(2000).queue(function(){ $(this).removeClass("classadded").dequeue(); }); });
Demo: http://jsfiddle.net/z2tetyj4/
Overview
- .delay() is a timer to delay execution for a specific amount of time.
- .dequeue() executes the next function sitting in the queue.
Example # 7: How to add a specific class to every other div (Even)
If you have a list of blog items with same div structure, and you want to add a specific class to the 2nd, 4th, etc. with jQuery, then try the following code:
HTML
<div class="bloglist"> <div class="post"> <h3>Post 1</h3> </div> <div class="post"> <h3>Post 2</h3> </div> <div class="post"> <h3>Post 3</h3> </div> <div class="post"> <h3>Post 4</h3> </div> </div>
CSS
.newclass { background-color:#0C9; }
jQuery
$(document).ready(function() { $(".post:nth-child(even)").addClass("newclass"); });
Demo: http://jsfiddle.net/cc4gt84s/
Overview
- :nth-child() is used to get all the elements that are nth-child of their parent element. The value of :nth-child() could be a number (e.g. 1, 2, 3), the string odd or even, or an equation.
Example # 8: How to add a new class to the same element every two seconds
If you don’t know a way to change the background color of a div after every two seconds, then following is the code for you to follow:
HTML
<div id="bg"></div>
CSS
div { background-color:#F00; width:200px; height:200px; } .brown { background-color: #a52a2a; } .cadetblue { background-color: #5f9ea0; } .cornflowerblue { background-color: #6495ed; } .darkgolden { background-color: #b8860b; } .black { background-color: #000000; }
jQuery
$(document).ready(function() { var $getDiv = $('div#bg'), classNames = ['brown', 'cadetblue', 'cornflowerblue', 'darkgolden', 'black'], interval = window.setInterval(function() { if (classNames.length === 0) window.clearInterval(interval); $getDiv.addClass(classNames.shift()); }, 2000); });
Demo: http://jsfiddle.net/08t3uw34/
Overview
The important thing used here is window.setInterval and its ability to accept a callback function that is executed every millisecond. Plus, the above code won’t run forever because a unique integer id is passed to window.clearInterval function.
Example # 9: How to add unique classes to ul.sub-menu in WordPress using jQuery
By default, WordPress doesn’t provide a way to assign unique classes to ul.submenu. So, in this example, we will try to solve this by using jQuery.
HTML
<ul id="menu-primary" class="nav"> <li class="menu-item">Item 1 <ul class="sub-menu"> <li class="menu-item">Item 1.1</li> <li class="menu-item">Item 1.2</li> </ul> </li> <li class="menu-item">Item 2 <ul class="sub-menu"> <li class="menu-item">Item 2.1</li> <li class="menu-item">Item 2.2</li> </ul> </li> <li class="menu-item">Item 3 <ul class="sub-menu"> <li class="menu-item">Item 3.1</li> <li class="menu-item">Item 3.2</li> </ul> </li> </ul>
jQuery
$(document).ready(function() { $('ul.sub-menu').each(function(index) { $(this).addClass("item-" + index); }); });
Demo: http://jsfiddle.net/3q1ra4cu/
Example # 10: How to create simple jQuery accordion with addClass and removeClass
In this example, you will learn to create accordion using jQuery.
HTML
<div class="accordion"> <h3>Heading 1</h3> <p style="display:none;">Content 1</p> <h3>Heading 2</h3> <p style="display:none;">Content 2</p> </div>
jQuery
$(document).ready(function() { $(".accordion > h3").click(function(){ $('.active').removeClass('active'); $(this).addClass('active'); $(this).next().slideToggle(600); }); });
Demo: http://jsfiddle.net/m9qsumpv/
Overview
- .next() is used to get the next sibling of a specified element.
- .slideToggle() is used to hide and show in a sliding motion. Sliding speed is determined by the value given in parenthesis (). The default value is 400 milliseconds.
Example # 11: How to add a class when a checkbox is checked
In this example, we will add a class when a checkbox is checked, and else the class will be removed.
HTML
<input type="checkbox" class="checkbox_check" />Check Me <h3 style="display:none;">Text</h3>
jQuery
$(document).ready(function() { $('.checkbox_check').change(function() { if ($(this).prop('checked')) { $("h3").addClass('class_added'); $("h3").text("Class Added"); $("h3").css("display", "block"); } else { $("h3").removeClass('class_added'); $("h3").text("Class Removed"); $("h3").css("display", "block"); } }); });
Demo: http://jsfiddle.net/90m5nzq4/
Example # 12: If image’s height is greater than the width, add a class.
In this example, we will try to add a class if the height of an image is greater than the width.
HTML
<img class="imgsize" src="https://www.visiospark.com/wp-content/uploads/2013/10/sakaguchi.png" alt="img" />
CSS
.new_class {border:1px solid; }
jQuery
$(document).ready(function() { var getImage = $('.imgsize'); var imgWidth = getImage.width(); var imgHeight = getImage.height(); if(imgHeight > imgWidth) { getImage.addClass('new_class'); } });
Demo: http://jsfiddle.net/48n24xx0/
Here, .width() and .height() are used to calculate the width and height simultaneously.
Example # 13: Adding a class with select box (drop down) and jQuery
In this example, we are going to create a drop-down having color names. When an option selected, the background color of the “h1” tag will be filled with the selected color.
HTML
<select name="select1"> <option>Blue</option> <option>Green</option> <option>Yellow</option> </select> <h1 class="select1">This is sample text</h1>
CSS
.blue {background-color: blue; } .green {background-color: green; } .yellow {background-color: yellow; }
jQuery
$(document).ready(function() { $('select').change(function(){ var $this = $(this); var values = $.map($this.find('option'),function(opt){ return opt.value.toLowerCase(); }).join(' '); $('.'+this.name).removeClass(values).addClass($(this).val().toLowerCase()); }); });
Demo: http://jsfiddle.net/9e61tgu0/
I know, you are going to learn a lot from this post “13 ways to use addClass().” The examples demonstrated above are the real life examples that I faced when working on client’s websites. Do not hesitate to comment down below. Feel free to suggest us more examples on jQuery addclass.