Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to toggle class using pure javascript in html

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

like image 287
user2906766 Avatar asked Nov 30 '13 14:11

user2906766


People also ask

How do I toggle a class in JavaScript?

Toggling the class means if there is no class name assigned to the element, then a class name can be assigned to it dynamically or if a certain class is already present, then it can be removed dynamically by just using the toggle() or by using contains(), add(), remove() methods of DOMTokenList object within JavaScript ...

How do you toggle between classes in HTML?

Toggle Class Toggle between adding a class name to the div element with id="myDIV" (in this example we use a button to toggle the class name).

How do you add toggle in HTML?

We can do that by using the HTML label tag and HTML input type = checkbox. HTML code: The HTML code is used to create a structure of toggle switch. Since it does not contain CSS so it is just a simple structure.

How is toggle used in JavaScript?

The toggle() method toggles between hide() and show() for the selected elements. This method checks the selected elements for visibility. show() is run if an element is hidden. hide() is run if an element is visible - This creates a toggle effect.


1 Answers

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> 
like image 168
Tom Chung Avatar answered Oct 12 '22 10:10

Tom Chung