How to addclass jquery – javascript add class

For a frontend programmers is vital to know how to add a class on click, or when document is ready.

There is nothing complicated in adding a class when an element is clicked. Here we will learn all necesary steps to add a class.

The first thing we have to do is load up the jquery library, to do that we have to put the following line of code before all script in the html file. 

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

 

We still have to create a new file that we will name "script.js", in our new file we will have to following script:

jQuery(function(){
jQuery('.trigger').on('click', function(){
jQuery('body').addClass('my_class');
});
});

 

 In the above script the first thing we do is to check if the document is ready or not, then we will click on the element which has class "trigger" then add the class "my_class" on body.

 

And the HTML:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="trigger"></div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</html>

 

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x