Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

jQuery .hover

Hi friends.

I want the background color of a selector turns yellow when I hover in and that when I hover out it returns to its original color. here is the code i am trying:

$(".event").hover(
      function () {
            $(this).addClass("hoverNow"); 
            $(".hoverNow").css("background-color","yellow");    
    },
      function () {
            $(this).removeClass("hoverNow"); 
    }); 

it works when I hover in but it doesn't remove the color when I hover out, plz can someone explain me why ?

I know that I can add the class styling via the css sheet or use another way to make it work , however I just want to understand why this way isn't working. thx.

1 Answer

The key to understanding what is happening here is to open up the console and observe what is happening to the elements on the page when you hover over the element.

You will see that when you hover with your code it will add the specified class. It will then add the background color via the style tag so you would have something like this:

<div id="main" class="hoverNow" style="background-color: yellow">

When you stop hovering over the element your code tells the page to remove the class. So the class is removed, but the background color styling remains on the element. I couldn't find a jquery method to remove css styling. So it seems that the only way to fix this would be add a line of code to change the color back to what the original styling was. So it would look something like this:

$("#main").hover(function (){
    $(this).addClass("hover")
    $(".hover").css("background-color", "yellow")
}, function () {
    $(".hover").css("background-color", "blue")
    $(this).removeClass("hover")
});

However, if you are only changing the background color and the hover class doesn't contain any additional styling then it would probably be unnecessary. You could get away with just using the css() method or as you said earlier, just add the styling to the class on the css page and use jquery to add and remove that class

That's what I was afraid of, but thx anyway for the help.