Add active class onclick javascript


Learn how to add an active class to the current element with JavaScript.


Highlight the active/current (pressed) button:

Try it Yourself »


Active Element

Step 1) Add HTML:

Example


 
 
 
 
 


Step 2) Add CSS:

Example

/* Style the buttons */
.btn {
  border: none;
  outline: none;
  padding: 10px 16px;
  background-color: #f1f1f1;
  cursor: pointer;
}

/* Style the active class (and buttons on mouse-over) */
.active, .btn:hover {
  background-color: #666;
  color: white;
}



Step 3) Add JavaScript:

Example

// Get the container element
var btnContainer = document.getElementById("myDIV");

// Get all buttons with class="btn" inside the container
var btns = btnContainer.getElementsByClassName("btn");

// Loop through the buttons and add the active class to the current/clicked button
for (var i = 0; i < btns.length; i++) {
  btns[i].addEventListener("click", function() {
    var current = document.getElementsByClassName("active");
    current[0].className = current[0].className.replace(" active", "");
    this.className += " active";
  });
}

Try it Yourself »

If you do not have an active class set on the button element to start with, use the following code:

Example

// Get the container element
var btnContainer = document.getElementById("myDIV");

// Get all buttons with class="btn" inside the container
var btns = btnContainer.getElementsByClassName("btn");

// Loop through the buttons and add the active class to the current/clicked button
for (var i = 0; i < btns.length; i++) {
  btns[i].addEventListener("click", function() {
    var current = document.getElementsByClassName("active");

    // If there's no active class
    if (current.length > 0) {
      current[0].className = current[0].className.replace(" active", "");
    }

    // Add the active class to the current/clicked button
    this.className += " active";
  });
}

Try it Yourself »



I am trying to make a navigation menu I did all the HTML and CSS when come to javascript I am struck in the middle I am able to add a class to the element, but I am not able to remove the class remaining elements. Please help me with this.
here is my code


    
    
        Navigation class Toggling

        
    
    
    

and here is my Codepen

Add active class onclick javascript

asked Aug 17, 2016 at 7:06

3

Use document.querySelectorAll to find the element which currently have the active class, then you can remove that class.

function myFunction(e) {
  var elems = document.querySelectorAll(".active");
  [].forEach.call(elems, function(el) {
    el.classList.remove("active");
  });
  e.target.className = "active";
}

JSFIDDLE

Instead of document.querySelectorAll you can also use document.querySelector

 function myFunction(e) {
  var elems = document.querySelector(".active");
  if(elems !==null){
   elems.classList.remove("active");
  }
 e.target.className = "active";
}

JSFIDDLE 2

Edit

Instead of iterating through the entire collection you can select the element which have a class active using document.queryselector. Also provide an id to the ul so that you can target the specific element

function myFunction(e) {
  if (document.querySelector('#navList a.active') !== null) {
    document.querySelector('#navList a.active').classList.remove('active');
  }
  e.target.className = "active";
}

    
    
    

answered Aug 17, 2016 at 7:19

Add active class onclick javascript

Dinesh ShahDinesh Shah

1,1331 gold badge7 silver badges13 bronze badges

1

I'd personally stick with the document.querySelector method. querySelector accepts a CSS like query, which we will use to find an active class on the page. If it exists (the if statement), remove it and apply the new class on the target.

Please be aware that using className = "" will result in all classes being removed. It would be more neat to use classList for everything.

function myFunction(e) {
    var el = document.querySelector('.active');
  
    // Check if the element exists to avoid a null syntax error on the removal
    if(el) {
      el.classList.remove('active');
    }
		
    e.target.classList.add('active');
}

answered Aug 17, 2016 at 7:21

Add active class onclick javascript

roberrrt-sroberrrt-s

7,7122 gold badges45 silver badges55 bronze badges

Below should help.

//Remove all classes by ID
document.getElementById("elementIdHere").className = "";
//If you wish to keep some classes on the element, use below
document.getElementById("elementIdHere").className = "keepClass";

answered Aug 17, 2016 at 7:12

Add active class onclick javascript

IronAcesIronAces

1,7551 gold badge25 silver badges34 bronze badges

1

JS

var targets = document.querySelectorAll('.some-class');

targets.onclick = function(evt) {
    evt.classList.toggle('{your-class}');
};

For better browser support:

targets.onclick = function(evt) {
    var el = evt.target;
    var classes = el.className.split(" ");
    var classIndex = classes.indexOf('{your-class}');

    if (classIndex >= 0) {
        classes.splice(1, classIndex);
    } else {
        classes.push('{your-clas}');
    }

    el.className = classes.join(" ");
});

answered Aug 17, 2016 at 7:43

window.myFunction = function(event) {
  var elms = document.querySelectorAll('ul li a');
  // reset all you menu items
  for (var i = 0, len = elms.length; i < len; i++) {
    elms[i].classList.remove('active');
  }
  // mark as active clicked menu item
  event.target.classList.add("active");
};
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

header {
  width: 100%;
  height: auto;
  max-width: 600px;
  margin: 0 auto;
}

nav {
  width: 100%;
  height: 40px;
  background-color: cornflowerblue;
}

ul {
  list-style-type: none;
}

li {
  display: inline-block;
}

a {
  text-decoration: none;
  padding: 8px 15px;
  display: block;
  text-transform: capitalize;
  background-color: pink;
  color: #fff;
}

a.active {
  background-color: blue;
}

.active {
  ackground-color: red;
}

answered Aug 17, 2016 at 8:31

How do you add active class on click event?

In Bootstrap 4, Javascript or jQuery events are used to add active class on click event in custom list group. Syntax: $(document). ready(function() { $('selector').

How do you make an active class in Javascript?

We are using this keyword to get the currently clicked button element and adding an active class to it using add() method..
let buttons = document. querySelectorAll('button'.
buttons. forEach(button =>.
button. addEventListener function () {.
buttons. forEach(btn btn. classList. ... .
this. classList. add('active'.

How do you add active class to clicked item in Reactjs?

How to Add Active Class to Clicked Item in React Js Mapped Items.
Step 1: Install React Project..
Step 2: Add Bootstrap Module..
Step 3: Create Component File..
Step 4: On Clicked Add Active Class to Mapped Item..
Step 5: Update App Js Component..
Step 6: View App in Browser..