How TO - Add Active Class to Current Element

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP





googletag.cmd.push(function() googletag.display('div-gpt-ad-1422003450156-2'); );



How TO - Add Active Class to Current Element



❮ Previous
Next ❯


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



Highlight the active/current (pressed) button:











// Add active class to the current button (highlight it)
var header = document.getElementById("myDIV");
var btns = header.getElementsByClassName("btn");
for (var i = 0; i < btns.length; i++)
btns[i].addEventListener("click", function()
var current = document.getElementsByClassName("activehr");
current[0].className = current[0].className.replace(" activehr", "");
this.className += " activehr";
);

Try it Yourself »

Active Element


Step 1) Add HTML:


Example



<div id="myDIV">
  <button class="btn">1</button>
  <button
class="btn active">2</button>
  <button class="btn">3</button>
 
<button class="btn">4</button>
  <button class="btn">5</button>

</div>



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;








googletag.cmd.push(function() googletag.display('div-gpt-ad-1493883843099-0'); );





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 »




❮ Previous
Next ❯

Popular posts from this blog

California

New York City

CNN