Toggle class on HTML element without jQuery

后端 未结 7 1466
时光说笑
时光说笑 2020-12-08 14:27

I have a section on my website which holds all the content, but I want a \"sidebar\" with hidden content to smoothly appear from the left at the push of an external button.<

7条回答
  •  离开以前
    2020-12-08 15:09

    You can toggle classes using the classList.toggle() function:

    var element = document.getElementById('sidebar');
    var trigger = document.getElementById('js-toggle-sidebar'); // or whatever triggers the toggle
    
    trigger.addEventListener('click', function(e) {
        e.preventDefault();
        element.classList.toggle('sidebar-active'); // or whatever your active class is
    });
    

    That should do everything you need - if you have more than one trigger I'd recommend using document.querySelectorAll(selector) instead.

提交回复
热议问题