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.

Comments

  1. User Avatar
    Rodge
    Permalink to comment#

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

    • User Avatar
      Alex Mcvitie
      Permalink to comment#

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

    • User Avatar
      Pizatski
      Permalink to comment#

      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!

    • User Avatar
      karim
      Permalink to comment#

      absolutly :

      $(‘.element’).hover(
      function(){$(this).toggleClass(‘classname’);}
      );

    • User Avatar
      Rūta
      Permalink to comment#

      Thank you :)

  2. User Avatar
    Kaplan
    Permalink to comment#

    Simple but great code snippet.
    Thnx…

  3. User Avatar
    Matt
    Permalink to comment#

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

  4. User Avatar
    David
    Permalink to comment#

    You saved my life. thx

  5. User Avatar
    Attila Hajzer
    Permalink to comment#

    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.

    • User Avatar
      Brannon
      Permalink to comment#

      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. User Avatar
    omarxp studio
    Permalink to comment#

    thank you, I always forget this way.

  7. User Avatar
    Tim
    Permalink to comment#

    I’m new to javascript–could you post or point me to a demo of this in action?

    I tried replacing the #elm with the ID of my div, and the ‘hover’ with my new class, like this:

    
    	
    	
    	$('#test').hover(
           function(){ $(this).addClass('test-grey') },
           function(){ $(this).removeClass('test-grey') }
    	)
    	
    
    

    Then I styled the new class. How did I break it?

  8. User Avatar
    Peter Garrett
    Permalink to comment#

    Tim, you’ll find that you are applying both the add and remove class at the same time here…

    You’ll need to apply the remove class on a different event…

  9. User Avatar
    Aahan Krish
    Permalink to comment#

    @Tim: It’s jQuery. Try this:

    jQuery(document).ready(function($){
        $('#test').hover(
             function(){ $(this).addClass('test-grey') },
             function(){ $(this).removeClass('test-grey') }
        )
    });
    

    You need to make sure that jQuery library is referenced on the page (see code below) and that the aforementioned code comes AFTER it.

    <script src='http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js'></script>
    

    Then make sure that your HTML code contains something like this:

    <div id="test" class="">Some content here....</div>
    

    So, when you open the web page, and hover your mouse over the div, it’d look like this:

    <div id="test" class="test-grey">Some content here....</div>
    

    And when move your away from the div, it’d again become:

    <div id="test" class="">Some content here....</div>
    

    Similarly, you can also target classes:

    jQuery(document).ready(function($){
        $('.test').hover(
             function(){ $(this).addClass('test-grey') },
             function(){ $(this).removeClass('test-grey') }
        )
    });
    

    In which case, your HTML code should look like:

    <div class="test">Some content here....</div>
    

    @PeterGarrett: Are you sure? I think we need both lines, otherwise it doesn’t seem to work. ↑

  10. User Avatar
    sunil

    Thanks @Aahan
    it’s very helpful to me …

  11. User Avatar
    erick bett
    Permalink to comment#

    I think the removeClass should come first in order to remove any previous added class first before adding class.

  12. User Avatar
    Paul
    Permalink to comment#

    @erick jQuery’s addClass handles that logic, it won’t add if the class exists already.

     $(document.createElement('div')) 
                .addClass('test')
                .addClass('test')
                .attr('class');  //returns "test"
    
  13. User Avatar
    Ger
    Permalink to comment#

    I am trying to remove hover only from a smallButton class without the whole class. I am trying just to remove button.smallButton:hover and keep .smallButton in use. Is this possible:

    jQuery(document).ready(function($){
    $(‘#buttonId’).hover(
    function(){ $(this).removeClass(‘button.smallButton:hover’)}
    )
    });

  14. User Avatar
    shazz
    Permalink to comment#

    a:hover{ color:#666;}

  15. User Avatar
    Tom
    Permalink to comment#

    Hey, this was so great!! I am super excited about figuring this out. I used this (in part) to build a menu that I really needed to add to in SharePoint.

    I needed a toggle for the active class and this gave me the framework to get that done.

  16. User Avatar
    Kevin
    Permalink to comment#

    If you want to toggle between 2 different classes rather than add and remove a single class as I did in my shopping basket page then this works…

    $('#quantity_more_' + line_item_id).hover(
       function() {
          $(this).addClass('fa-plus-square-o');
          $(this).removeClass('fa-plus-square')
       }, function() {
          $(this).addClass('fa-plus-square');
          $(this).removeClass('fa-plus-square-o')
       }
    );
    

    (Note: I also have similar code for ‘fa-minus-square’ and ‘fa-minus-square-o’ on my ‘#quantity_less_’ + line_item_id control)

Submit a Comment

Posting Code

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.

icon-anchoricon-closeicon-emailicon-linkicon-logo-staricon-menuicon-nav-guideicon-searchicon-staricon-tag