Targeting Specific Divs
Question
Ok, what I'm trying to figure out it how to use jQuery to work out which div
is currently selected, highlights, etc and then to apply code to that div
.
For example, I have three div
s lined up in a row. Each div
has a class
of .box
. Within each div
is another div
with a class of .overlay
. By default .overlay
is set to display: none;
, but when I roll the mouse over each div
I want to overlay for THAT div
ONLY to get set to become visible - all the other div
s overlay should remain hidden.
Take a look, http://jsfiddle.net/j76s2/
I've got the JS to get the overlay to show when the mouse rolls over the div
s, but it shows all the overlays whenever you roll the mouse over any div
. I know why that's happening but what I can't work out is how to get the code to work out that is should only show the overlay for the first div
when that div
has the mouse over it and so on.
Solution
You can use the .hover()
event which takes two functions, one for hoverin and one for hoverout. And, then you can use this
as the context for the currently hovered .box
element to find the .overlay
in it and then use .hide()
and .show()
to change it's visibility.
$(".box").hover(
function(){$(this).find(".overlay").show()},
function(){$(this).find(".overlay").hide()}
);
Working demo: http://jsfiddle.net/jfriend00/wa5Bn/
You may also like to use fadeIn()
and fadeOut()
like this:
$(".box").hover(
function(){$(this).find(".overlay").stop(true, true).fadeIn(500)},
function(){$(this).find(".overlay").stop(true, true).fadeOut(500)}
);
Working demo: http://jsfiddle.net/jfriend00/4qeqm/
OTHER TIPS
You just need to refer to specific element with this
:
$(".box").mouseover(function(){
$(".overlay", this).css({"display" : "block"});
});
$(".box").mouseleave(function(){
$(".overlay", this).css({"display" : "none"});
});
This way you are narrowing the selection to a .box
element contained inside hovered element.
Also, consider using .hide()
and .show()
instead of .css()
.
You are changing the CSS for all of the elements with the .overlay
class. To just affect the one that you are currently mousing over, you should use $(this)
to select the current element, and then find()
to locate the class that is contained within it.
$(".box").mouseover(function(){
$(this).find(".overlay").css({"display" : "block"});
});
$(".box").mouseleave(function(){
$(this).find(".overlay").css({"display" : "none"});
});