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
cesarguido
2,699 PointsQuestion about Hover
Hi guys, can someone explain me how the hover function works when you hover out from an element?
example:
$(document).ready(function(){
$("div").hover(
function(){
$(this).add Class("active")
},
function(){
$(this).remove Class("active")
}
);
});
I understand that when you hover in, query adds a class but what tells query when it has to remove the class? I don't see any hover Out function or something like that.
Thx
2 Answers
Dave McFarland
Treehouse TeacherHi cesarguido
The hover() method takes two functions as arguments -- the first function runs when the mouse enters the element (mouse onto) and the second function runs when the mouse leaves the element (mouses off).
As for your question: if the element already has an "active" class on it, when you mouse onto the element jQuery DOES NOT add a second "active" class. When you mouse off, jQuery does remove the "active" class.
In other words, the first function is ONLY applied when the mouse is placed over the element, and the second function ONLY runs when the mouse leaves the element.
cesarguido
2,699 Pointsthx very much!! by the way, I did your course here and you are a very good teacher. Is very nice to see that you have the time to answer simple questions.
Dave McFarland
Treehouse TeacherYou are welcome cesarguido
I'm glad I could help.
cesarguido
2,699 Pointsthx for the reply mate, however am going to ask this another way: what happens if I hover( staying in) and I already have a class "active" in my html:
the first part adds another "active" class ( having 2 now) and the second part removes one (leaving it at one again)?
does both actions happen simultaneously ?
in this is the case I think I know how the hover works.
Adam Jarrell
8,817 PointsAdam Jarrell
8,817 PointsFirst, add semicolons after your .addClass(); and .removeClass(); functions. It's a good habit to end whole lines of code not broken by line breaks with semicolons. Also, remove the spaces in addClass(); and removeClass();.
Anyway, when you remove your cursor from the element which you are hovering the second function in your hover statement is executed. That is, the function which removes the class is executed or the function after the comma in the .hover expression.