Newbie question: I have a loop which places a number of elements on a page, but when I reference the IDs I can only select the first one. Can someone tell me how I can apply the hover function to the items?
I am trying to achieve a page of dots, where each one fades in and out when hovered over. At the moment it just goes haywire when I select the first dot, and none of the others respond. Thanks in advance!
var dots = '';
for (i = 0; i < 100; i++) {
dots += '<div id="dot" class="blue"> </div><div id="dot" class="red"> </div><div id="dot" class="grey"> </div>';
}
//insert all
$('body').append(dots);
// dot hover
$('#dot').hover(function() {
$(this).stop().fadeOut(200);
}, function() {
$(this).stop().fadeIn(400);
});
});
idattributes must be unique within each page but you’re repeating them, that’s why$('#dot')only finds the first one. HTML4 has this to say:And HTML5:
You should be using a class instead: