How to toggle class using pure javascript in html

JavascriptHtmlCssHoverToggle

Javascript Problem Overview


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!!

Javascript Solutions


Solution 1 - Javascript

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>

Solution 2 - Javascript

While Tom Chung's approach definitely works, it's better to give mouseenter and mouseleave their own handler :

<div id="container" class="first">
    TEST
</div>

.first {
    background: green;
}

.second {
    background: orange;
}

var container = document.querySelector('#container');

container.addEventListener('mouseenter', function(){
        this.classList.remove('first');
        this.classList.add('second');
})
container.addEventListener('mouseleave', function(){
        this.classList.add('first');
        this.classList.remove('second');
})

(see also this Fiddle)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser2906766View Question on Stackoverflow
Solution 1 - JavascriptTom ChungView Answer on Stackoverflow
Solution 2 - JavascriptJohn SlegersView Answer on Stackoverflow