add active class onclick javascript

Today, We want to share with you add active class onclick javascript.In this post we will show you toggle active class javascript, hear for javascript add active class to current page we will give you demo and example for implement.In this post, we will learn about Dynamically addClass CSS click using jQuery with an example.

How To Add Active Class To Current Element?

add / remove active class

HTML Code

<div class="container">
  <ul class="nav">
      <li>Laptop</li>
      <li>Mobile</li>
      <li>Iphone</li>
      <li>Watch</li>
  </ul>
</div>

CSS Code

li.active {
    color: green;
}

Simple jQuery

var selector = '.nav li';

$(selector).on('click', function(){
    $(selector).removeClass('active');
    $(this).addClass('active');
});

Highlight the active/current (pressed) button:

index.html

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.btn {
  border: none;
  outline: none;
  padding: 10px 16px;
  background-color: #f1f1f1;
  cursor: pointer;
  font-size: 18px;
}

/* Style the active class, and buttons on mouse-over */
.active, .btn:hover {
  background-color: #666;
  color: white;
}
</style>
</head>
<body>

<h1>Active Button</h1>
<p>Highlight the active/current (pressed) button.</p>
  
<div id="allProducts">
  <button class="btn">1</button>
  <button class="btn">2</button>
  <button class="btn">3</button>
  <button class="btn">4</button>
  <button class="btn">5</button>
</div>

<script>

var header = document.getElementById("allProducts");
var btns = header.getElementsByClassName("btn");
for (var i = 0; i < btns.length; i++) {
  btns[i].addEventListener("click", function() {
  var getcname = document.getElementsByClassName("active");
  if (getcname.length > 0) { 
    getcname[0].className = getcname[0].className.replace(" active", "");
  }
  this.className += " active";
  });
}
</script>

</body>
</html>

I hope you get an idea about add active class after page load jquery.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

Also Read This 👉   jquery add active class to current menu item