64

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

John Slegers
  • 45,213
  • 22
  • 199
  • 169
user2906766
  • 863
  • 3
  • 10
  • 12

2 Answers2

62

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>
Tom Chung
  • 1,412
  • 9
  • 12
  • 6
    When using `ID` (`#container`) the oldschool `getElementById()` is almost 10x faster than `querySelector()` – Roko C. Buljan Apr 01 '14 at 07:42
  • 4
    Note that the `.toggle()` method is not supported on IE9 and under. See [MDN Docs on `classList`](https://developer.mozilla.org/en-US/docs/Web/API/Element/classList) – Bradley Flood Mar 05 '15 at 03:34
  • In some edge cases, JS is better for complete cross browser compatibility. – MaxRocket Jul 13 '18 at 18:18
10

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

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');
})
.first {
    background: green;
}

.second {
    background: orange;
}
<div id="container" class="first">
    TEST
</div>

(see also this Fiddle)

Community
  • 1
  • 1
John Slegers
  • 45,213
  • 22
  • 199
  • 169