#StandWithUkraine

AucT Blog

Simple Javascript (JS) Toggle

Method #1

This method is good for small projects where you just need to fast toggle some block.
If your element has something in display you should use method #2

Code:

<script>function toggle(el) {
  el.style.display = (el.style.display == '') ? 'none' : ''</script>
}

Usage:

<div id="block" style="display:none;">Random toggle text</div>
<span onclick="toggle(document.getElementById('block'))">Click Me!</span>

Example:

Click Me!

Method #2

This method adds/removes class from element, so if you have something in display attribute everything will be fine

Code:

<style>
.none{display:none;}
</style>
<script>
function toggle(el) {
  if (hasClass(el,'none'))
	removeClass(el,'none');
  else
	addClass(el,'none');
}
function hasClass(ele,cls) {
    return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}
function addClass(ele,cls) {
    if (!this.hasClass(ele,cls)) ele.className += " "+cls;
}
function removeClass(ele,cls) {
    if (hasClass(ele,cls)) {
        var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
        ele.className=ele.className.replace(reg,' ');
    }
}
</script>

Usage:

<div id="block" class="none">Random toggle text</div>
<span onclick="toggle(document.getElementById('block'))">Click Me!</span>

Example:

Random toggle text
Click Me!

Share on Social Networks:

Twitter Facebook
comments powered by Disqus