user1303274
user1303274

Reputation: 1

Pass the image id to a function and show/hide();

I've four images with IDs img01, img02, img03, img04.

Another four images are added to an array to show that they are related to each image mentioned above, like IDs hover01, hover02, hover03, hover04.

How to write a common function to show the hover image related to each? That is, each time when the mouse is over an image, an argument should be passed to a function to show.

Hope that makes sense.

Upvotes: 0

Views: 337

Answers (2)

Andreas Louv
Andreas Louv

Reputation: 47099

$("img[id^=img]").each(function() {
    var number = ( this.id + "" ).replace("img", "");
        relatedImg = $("#hover" + number );
});

$("img[id^=img]") selects all images having an ID starting with img.

relatedImg is the hover image.


var getHover = function(myId) {
    var number = ( myId + "" ).replace("img", "");
    return $("#hover" + number );
}

var hoverImage = getHover("img01");

if you have the ID already you can use getHover to get the hover image.

Upvotes: 1

jfriend00
jfriend00

Reputation: 707426

Assuming you had img tags like this:

​<img class="hoverImage" id="img01" src="xxx">​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

You could use code like this to get the id of the hovered image, extract the number off the end, add a new prefix onto it and show/hide an image with that newly constructed ID:

function makeHoverSelector(str) {
    var matches = str.match(/\d+$/);
    if (matches) {
        return("#hover" + matches[0]);
    }
    return("#missingImage");
}

$(".hoverImage").hover(function() {
    $(makeHoverSelector(this.id)).toggle();
});​

Upvotes: 0

Related Questions