I try to accomplish a list of elements on which you hover a different image are displayed.
Something like this
<ul id="test">
<li id="sidebarList_1">Image 1</li>
<li id="sidebarList_2">Image 2</li>
<li id="sidebarList_3">Image 3</li>
<ul>
<div id="imgDiv_1">
<img src="http://www.freemacware.com/wp-content/images/smultron1.png" />
</div>
<div id="imgDiv_2">
<img src="http://www.freemacware.com/wp-content/images/smultron2.png" />
</div>
<div id="imgDiv_3">
<img src="http://www.freemacware.com/wp-content/images/smultron3.png" />
</div>
My jQuery looks like this
$(this).mouseover(function() {
$("#imgDiv_1").css('visibility','visible');
}),
$(this).mouseout(function() {
$("#imgDiv_1").css('visibility','hidden');
});
As seen it is static as it is now. I tried something like this to get the number of the id element in the li (ex sidebarList_1):
$(this).mouseover(function() {
var myString = $(this).val().split("_").pop();
$("#imgDiv_" + myString).css('visibility','visible');
}),
$(this).mouseout(function() {
var myString = $(this).val().split("_").pop();
$("#imgDiv_" + myString).css('visibility','hidden');
});
But this does’nt work. How can I accomplish what Im trying to do?
I would add a
data-*attribute to yourlielements, whose value corresponds to the relevantdiv:And then use the following jQuery:
Here’s a working example.
This uses the
onmethod, with a selector as the second argument, to take advantange of event delegtation (there’s only one event handler instead of one for eachlielement). It assumes that thedivelements are hidden by default, so on mouseover, thetogglecall will make the hovereddivvisible.Useful references
.on()method.toggle()method.data()method