Monica M
Monica M

Reputation: 21

Getting an ID using Javascript and using it for mouseover event

Basically I want to shorten the amount of code I have to write. I'm trying to do a rollover with Javascript that will change the image to another and then change the image back once the mouse leaves the image. Right now this is what I have:

<a href="#" class="amc"><img src="img/characters/amc_card.png" class="amcIMG" /></a>

$(".amc").mouseenter(function() {
    $(".amcIMG").attr('src','img/characters/amc_card2.png');
});
$(".amc").mouseleave(function() {
    $(".amcIMG").attr('src','img/characters/amc_card.png');
});

I was hoping there was some way to store the ".amc" in a variable that gets that part from the rollover, and can do so for multiple images. All of my images are named similarly so if I can replace that ".amc" part with a variable that can change depending on the image it rollovers that should make it so I only have to write one function instead of well over 50. Please help!

Upvotes: 2

Views: 140

Answers (4)

Dave Jones
Dave Jones

Reputation: 344

Add an id to each img to give each a unique reference to each picture.

<a href="#"><img src="img/characters/amc_card.png" class="amc" id="amc_card" /></a>

$(document).ready(function(){
var amc = $(".amc");

amc.mouseenter(function() {
var id = this.id;
this.src = 'img/characters/'+ id +'2.png';
});
amc.mouseleave(function() {
var id = this.id;
this.src = 'img/characters/'+ id +'.png';
});

});

Upvotes: 0

hindmost
hindmost

Reputation: 7215

Try this:

function hover(el, on) {
    var img = $(el).children('img');
    var url = img.attr('src');
    var i = url.lastIndexOf('.');
    url = on? url.substr(0, i)+'2'+url.substr(i) : url.substr(0, i-1)+url.substr(i);
    img.attr('src',url);
}

$(".amc").mouseenter(function() {
    hover(this, true);
});
$(".amc").mouseleave(function() {
    hover(this, false);
});

Upvotes: 1

MplsAmigo
MplsAmigo

Reputation: 1025

Try this

function(){

    var amc= jQuery(".amc", jQuery("#Container"));

    jQuery(amc).on("mouseenter", "img", function(e){
        $(e.target).attr('src','img/characters/amc_card2.png');
    });

    jQuery(amc).on("mouseleave", "img", function(e){
        $(e.target).attr('src','img/characters/amc_card.png');
    });

}();

Keep in mind that anytime you use a class selector in jQuery it is going to search the entire DOM for every element containing that class which could cause a performance issue. You might consider narrowing its search by giving jQuery a context as I have done.

Upvotes: 2

andale
andale

Reputation: 473

Try:

$(".amc").mouseenter(function() {
    $(this).find('img').attr('src','img/characters/amc_card2.png');
});

Or more perfect way:

$(".amc").mouseenter(function() {
    $(this).children().attr('src','img/characters/amc_card2.png');
});

Upvotes: 1

Related Questions