I am trying to add a mouseup, mousedown, hover event on several different images – the only problem is that the event only occurs on the first image,
tried using the each() function does not seem to be working.
Any suggestions on how I can do this?
$(function() {
var filename = $('.imgover').attr('alt');
$('.rolloverimg').each(function(){
$('#'+ filename).mouseup(function(){
$(this).children("img").attr('src', 'content/images/buttons/'+ filename + '_up.png' );
}).mousedown(function(){
$(this).children("img").attr('src','content/images/buttons/' + filename + '_down.png');
});
$('#'+ filename).hover(
function () {
$(this).children("img").attr('src', 'content/images/buttons/'+ filename + '_hover.png');
},
function () {
$(this).children("img").attr('src', 'content/images/buttons/' + filename + '_up.png');
}
);
});
});
<div class="hdr-btns rolloverimg">
<a href="#"><img src="content/images/buttons/play_up.png" alt="play" id="play" class="imgover" /></a>
<a href="#"><img src="content/images/buttons/register_up.png" alt="register" id="register" class="imgover" /></a>
</div>
There is no need to implement a loop in order to add events to multiple elements using jQuery. You can simply apply the events to a selector that selects all the elements that you need.
For example, the following code adds MouseUp and MouseDown events to all the img tags inside an element that has the
rolloverimgclass:And if you want to quick test it, here is the full working example that was created starting from your source code:
Additional info update
If you do not want to select all the img tags from the div, but rather just the ones that have the
imgoverclass applied to them, you can use the following selector:Additional info update2
You can access the currently selected element using
$(this). For example:Please let me know if the above helps or if you need more specific help.