Code Snippet

Home » Code Snippets » jQuery » Adding/Removing Class on Hover

Adding/Removing Class on Hover

$('#elm').hover(
       function(){ $(this).addClass('hover') },
       function(){ $(this).removeClass('hover') }
)

This will work in any browser on any element, to support styling changes on hover.

Subscribe to The Thread

  1. Rodge

    isn’t it easier to use “toggleClass()” ????

    • There are many different ways to accomplish the same goal, its however invauable to know to many!

    • I realize this is about a year old, but the reason the add/remove class is more appropriate sometimes is if you have more than one trigger on a page for the same element. It’s simply more dummy-proof!

  2. Simple but great code snippet.
    Thnx…

  3. Thanks for the post, this works well when you want to be cross browser compatible and remove any :hover class’ from your CSS

  4. You saved my life. thx

  5. howcome it doesn’t work with .click but it works with hover? it doesn’t make sense. what i want is when you hover over a list item, then there’s the hover color, then when you click i have a div appear (sliding down) then i want the LI #Show to have a yellow background-color then when clicked again the div goes away Display:hidden) and then i want the LI#Show to go back to its regular state. but i canonly get so far. where if the li is clicked once, then the div appears and the li background goes yellow, but once i click it again the div dissappears but the color does not go away.

    • It could be that this code doesn’t work with click because it’s designed to use the old .hover() syntax, which requires two functions while .click() requires one. To start with, the method to use if you’re using jQuery 1.7 or higher is now .on() . For what you’re looking for, the right code might be something like this jsfiddle:

      http://jsfiddle.net/CodeJunkie/nMjMX/

  6. omarxp studio

    thank you, I always forget this way.

Speak, my friend

At this moment, you have an awesome opportunity* to be the person your mother always wanted you to be: kind, helpful, and smart. Do that, and we'll give you a big ol' gold star for the day (literally).

Posting tips:
  • You can use basic HTML
  • When posting code, please turn all
    < characters into &lt;
  • If the code is multi-line, use
    <pre><code></code></pre>
Thank you,
~ The Management ~