When I have 2 instances of grid, the jquery does not pick up the second grid list, but it does for the first. Both grids also work in Opera, Chrome, Safari and Firefox..just not IE.
html:
<ul id = grid>
<li><div class = "something><div class = hidden>hi</div></div></li>
<li><div class = "something><div class = hidden>hi</div></div></li>
<li><div class = "something><div class = hidden>hi</div></div></li>
</ul>
<ul id = grid>
<li><div class = "something><div class = hidden>hi</div></div></li>
<li><div class = "something><div class = hidden>hi</div></div></li>
<li><div class = "something><div class = hidden>hi</div></div></li>
</ul>
css:
.hidden
{
float: left;
display: none;
width: 150px;
height: 150px
}
.something
{
float: left;
width: 150px;
height: 150px
}
jQuery:
<script src="js/jquery.js"></script>
<script>
$(function() {
$("#grid li").hover(
function (e) {
var index = $('#grid li').index(this);
$(".hidden").eq(index).show();
},
function(e) {
var index = $('#grid li').index(this);
$(".hidden").eq(index).hide();
}
);
});
</script>
First you need to make your IDs unique, here is a good resource on how to create valid IDs: What are valid values for the id attribute in HTML?. You JS needs a little work to only select the .hidden
elements that are descendants of the grid you are currently hovering over and your class declarations for the .something
divs need a closing quote:
html:
<ul class = "grid">
<li><div class = "something"><div class = "hidden">hi</div></div></li>
<li><div class = "something"><div class = "hidden">hi</div></div></li>
<li><div class = "something"><div class = "hidden">hi</div></div></li>
</ul>
<ul class = "grid">
<li><div class = "something"><div class = "hidden">hi</div></div></li>
<li><div class = "something"><div class = "hidden">hi</div></div></li>
<li><div class = "something"><div class = "hidden">hi</div></div></li>
</ul>
jQuery:
<script src="js/jquery.js"></script>
<script>
$(function() {
//using the `.children()` function will be faster than $('.grid li')
$(".grid").children('li').hover(
function (e) {
//since $(this) gets used more than once its a good idea to cache it
var $this = $(this),
//to get an index you can just call `.index()` in an element and it will give you that element's index with respect to its siblings
index = $this.index();
$this.find(".hidden").eq(index).show();
},
function(e) {
var $this = $(this),
index = $this.index();
$this.find(".hidden").eq(index).hide();
}
);
});
</script>
Docs for .index()
: http://api.jquery.com/index
ID's must be unique. Try using a class instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With