How to toggle class using pure javascript in html

user2906766 picture user2906766 · Nov 30, 2013 · Viewed 85.6k times · Source

I have a <div>, and I want to toggle its classes on hover.

Here is my code:

function a(){
    this.classList.toggle('first');
    this.classList.toggle('sec');
}
document.querySelector('#container').addEventListener('click', a );

I know there is no problem in my html or css. It is just that I have to change and put something in place of click, but I don't know what.

Please help!!

Answer

Tom Chung picture Tom Chung · Nov 30, 2013

Hover event is called "mouseenter" instead of "click".

<script type="text/javascript">
    function a(){
        this.classList.toggle('first');
        this.classList.toggle('sec');
    }
    document.querySelector('#container').addEventListener('mouseenter', a )
    document.querySelector('#container').addEventListener('mouseleave', a )
</script>