jquery

13 Ways to Use In Different Scenarios

jQuery addclass() technique is used to add one or more courses to a specific aspect.

I feel you already know what jQuery .addClass() does, so why don’t we reduce to the chase and show you the 13 ways to use addClass() in several situations.

In the event you don’t know what jQuery .addClass() does, click on here.

Primary Syntax:

$(selector).addClass(‘a number of class names’);

Example # 1: Add class to a specific paragraph, however remove if another paragraph is chosen

Let’s say; you might have three paragraph parts, and also you want to spotlight selected paragraph on click.

HTML

First Paragraph

Second Paragraph

Third Paragraph

CSS

.selected
background-color: #000000;
colour: #ffffff;

jQuery

$(doc).prepared(perform()
$(‘p’).on(‘click on’, perform()
$(‘p’).removeClass(‘chosen’);
$(this).addClass(‘chosen’);
);
);

Demo: http://jsfiddle.net/cd9g72vw/

  • .on(): We used this technique to set off the press event handler.
  • .removeClass(): To remove the category “selected” from different not selected paragraphs.
  • $(this): To add the category “selected” on the clicked “p” factor.

Example # 2: Animation with .addClass() and CSS3

We’re going to accomplish this with the help of CSS3. Let’s see this in action:

HTML

CSS

#animation
    -webkit-transition: all 0.5s ease;
    -moz-transition: all zero.5s ease;
    -o-transition: all 0.5s ease;
    transition: all zero.5s ease;

.limegreen
    background-color: #32CD32;
    width: 150px;
    peak: 150px;

.lightblue
    background-color: #ADD8E6;
    width: 200px;
    peak: 200px;

jQuery

$(document).ready(perform()
         $(‘#animation’).hover(perform()
            $(this).addClass(‘lightblue’);
, perform()
            $(this).removeClass(‘lightblue’);
      );

);

The above example shouldn’t be tested on web explorer.

Demo: http://jsfiddle.net/w94aLtq6/

Overview

We used CSS3 transitions for the consequences and jQuery’s .addClass() for altering the class identify on “hover” within the above instance.


Instance # 3: Add a category on scrolling with jQuery and jQuery UI

With the help of jQuery and jQuery UI, add animation on scrolling down to 100px.

HTML

This is instance text

This is instance text

That is example textual content

That is instance textual content

This is instance textual content

This is instance text

This is example text

This is example textual content

That is example text

That is instance text

That is example text

That is example text

This is example textual content

That is example textual content

This is example textual content

This is example text

This is example text

This is instance text

CSS

.addnewclass
    colour: white;
    background-color: #000000;

jQuery

$(window).scroll(perform()
          var scroll = $(window).scrollTop();
          if (scroll >= 100)
                 setTimeout(perform()
                      $(“.nav”).addClass(“addnewclass”, 1000);
                , 500);
         
);

Demo: http://jsfiddle.net/sfufnp0h/

Overview

Don’t overlook to embrace jQuery UI library contained in the part of the HTML doc.

  • $(window).scroll() technique is used to trigger the scroll event when window is prepared.
  • .scrollTop() is used to get the present vertical position.
  • if (scroll >= 100) means, execute the code under if scrolling reached to 100px.
  • setTimeout() is used to execute the code after a specified time, in our case 500 milliseconds.

Instance # 4: Add class when there’s particular textual content discovered inside a div

Let’s say, you’ve gotten a div with numerous parts and textual content, and also you need to apply totally different styling to the div having a selected textual content. For this attempt our instance down under:

HTML

That is instance textual content

Text Found

Textual content Discovered

CSS

.addaclass
   shade: white;
   background-color: #add8e6;
   font-size:16px;

jQuery

$(doc).ready(perform()
       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 discovered, added the category “addaclass” to the div.

Example # 5: Change background shade by including a class on mouseover

In this instance, we are changing the background of a paragraph on .mouseover().

HTML

That is example textual content

CSS

.bg1
      background-color:#0C9;
       width: 150px;
       peak: 150px;

.bg2
       background-color: #30F;
       width: 150px;
       peak: 150px;

jQuery

$(document).prepared(perform()
               $(‘#changebg’).mouseover(perform()
                   $(this).addClass(‘bg2’);
                   $(this).removeClass(‘bg1’);
                );
               $(‘#changebg’).mouseout(perform()
                   $(this).addClass(‘bg1’);
                   $(this).removeClass(‘bg2’);
               );
);

Demo: http://jsfiddle.net/f4qeskc9/


Instance # 6: Add and take away a class after a delay

In this example, we’re going to add and take away a class after a delay. The jQuery methods used in this example are: addClass(), delay(), dequeue() and removeClass().

HTML

Sample Textual content

CSS

.classadded
    background-color:#0C9;
    width: 500px;
    peak: 150px;

jQuery

$(document).ready(perform()
     $(“#delay”).addClass(“classadded”).delay(2000).queue(perform()
          $(this).removeClass(“classadded”).dequeue();
     );
);

Demo: http://jsfiddle.net/z2tetyj4/

Overview

  • .delay() is a timer to delay execution for a selected amount of time.
  • .dequeue() executes the subsequent perform sitting in the queue.

Example # 7: How to add a selected class to each different div (Even)

If in case you have an inventory of weblog gadgets with similar div construction, and you want to add a selected class to the 2nd, 4th, and so forth. with jQuery, then attempt the following code:

HTML

Submit 1

Submit 2

Publish 3

Submit four

CSS

.newclass
      background-color:#0C9;

jQuery

$(doc).prepared(perform()
      $(“.post:nth-child(even)”).addClass(“newclass”);
);

Demo: http://jsfiddle.net/cc4gt84s/

Overview

  • :nth-child() is used to get all the weather which are nth-child of their father or mother factor. The worth of :nth-child() might be a quantity (e.g. 1, 2, 3), the string odd and even, or an equation.

Instance # 8: How to add a brand new class to the identical aspect every two seconds

Should you don’t know a means to change the background colour of a div after every two seconds, then following is the code for you to comply with:

HTML

CSS

div
      background-color:#F00;
      width:200px;
      peak:200px;

.brown
      background-color: #a52a2a;

.cadetblue
      background-color: #5f9ea0;

.cornflowerblue
      background-color: #6495ed;

.darkgolden
      background-color: #b8860b;

.black
      background-color: #000000;

jQuery

$(doc).prepared(perform()
   var $getDiv = $(‘div#bg’),
   classNames = [‘brown’, ‘cadetblue’, ‘cornflowerblue’, ‘darkgolden’, ‘black’],
    interval = window.setInterval(perform()
      if (classNames.length === 0)
         window.clearInterval(interval);
      $getDiv.addClass(classNames.shift());
   , 2000);
);

Demo: http://jsfiddle.net/08t3uw34/

Overview

The essential factor used here is window.setInterval and its means to accept a callback perform that’s executed every millisecond. Plus, the above code gained’t run endlessly because a singular integer id is handed to window.clearInterval perform.


Instance # 9: How to add distinctive courses to ul.sub-menu in WordPress using jQuery

By default, WordPress doesn’t present a means to assign unique courses to ul.submenu. So, on this instance, we’ll attempt to clear up this through the use of jQuery.

HTML

jQuery

$(doc).prepared(perform()
   $(‘ul.sub-menu’).every(perform(index)
      $(this).addClass(“item-” + index);
   );
);

Demo: http://jsfiddle.net/3q1ra4cu/


Instance # 10: How to create simple jQuery accordion with addClass and removeClass

In this example, you’ll study to create accordion using jQuery.

HTML

Heading 1

Content 1

Heading 2

Content material 2

jQuery

$(document).prepared(perform()
   $(“.accordion > h3”).click(perform()
      $(‘.lively’).removeClass(‘lively’);
      $(this).addClass(‘lively’);
      $(this).next().slideToggle(600);
   );
);

Demo: http://jsfiddle.net/m9qsumpv/

Overview

  • .next() is used to get the subsequent sibling of a specified factor.
  • .slideToggle() is used to disguise and present in a sliding motion. Sliding velocity is decided by the worth given in parenthesis (). The default worth is 400 milliseconds.

Example # 11: How to add a category when a checkbox is checked

In this example, we’ll add a class when a checkbox is checked, and else the class can be removed.

HTML

Verify Me

Text

jQuery

$(document).prepared(perform()
   $(‘.checkbox_check’).change(perform()
      if ($(this).prop(‘checked’))
         $(“h3”).addClass(‘class_added’);
         $(“h3”).textual content(“Class Added”);
         $(“h3”).css(“display”, “block”);
     
      else
         $(“h3”).removeClass(‘class_added’);
         $(“h3”).textual content(“Class Removed”);
         $(“h3”).css(“display”, “block”);
     
   );
);

Demo: http://jsfiddle.net/90m5nzq4/


Example # 12: If image’s peak is bigger than the width, add a category.

In this example, we’ll attempt to add a class if the peak of an image is bigger than the width.

HTML

img

CSS

.new_class border:1px strong;

jQuery

$(doc).ready(perform()
   var getImage = $(‘.imgsize’);
   var imgWidth = getImage.width();
   var imgHeight = getImage.peak();
   if(imgHeight > imgWidth)
      getImage.addClass(‘new_class’);
   
);

Demo: http://jsfiddle.net/48n24xx0/

Right here, .width() and .peak() are used to calculate the width and peak concurrently.


Example # 13: Including a category with choose field (drop down) and jQuery

In this example, we are going to create a drop-down having shade names. When an choice chosen, the background shade of the “h1” tag might be crammed with the selected colour.

HTML

That is pattern textual content

CSS

.blue background-color: blue;
.green background-color: green;
.yellow background-color: yellow;

jQuery

$(doc).ready(perform()
   $(‘choose’).change(perform()
      var $this = $(this);
      var values = $.map($this.find(‘choice’),perform(choose) return choose.value.toLowerCase(); ).be a part of(‘ ‘);
      $(‘.’+this.identify).removeClass(values).addClass($(this).val().toLowerCase());
   );
);

Demo: http://jsfiddle.net/9e61tgu0/

I know, you are going to study lots from this submit “13 ways to use addClass().” The examples demonstrated above are the actual life examples that I confronted when engaged on shopper’s websites. Don’t hesitate to comment down under. Be happy to recommend us more examples on jQuery addclass.