toggle() in javascript code example
Example 1: classname toggle js
document.getElementById('myButton').onclick = function() {
this.classList.toggle('active');
}
Example 2: toggle class to an element javascript
// html <div class="parentElm" id="addActive"></div>
// js
function toggleClass(){
// get the properties of an element
var element = document.getElementById("addActive");
// check if the element have class list
if (element.classList) {
// add active class if true
element.classList.toggle("active");
} else {
var classes = element.className.split(" ");
var i = classes.indexOf("active");
}
}
Example 3: javascript hide a div
<div id="main">
<p> Hide/show this div </p>
</div>
('#main').hide(); //to hide
// 2nd way, by injecting css using jquery
$("#main").css("display", "none");