alexleonard
alexleonard

Reputation: 1314

jquery getting this child to change img src

There's an old method I've used a lot to append a "-rollover" to an img to save me a lot of css rules but I've come across an instance where I can't get it to work.

Usually I just give the img a class of rollover and then use this jQuery:

$(".rollover").hover(function() {
    $(this).attr("src", $(this).attr("src").split(".").join("-rollover."));
}, function() {
    $(this).attr("src", $(this).attr("src").split("-rollover.").join("."));
});

However in this case the img is sitting in an element and I want the hover of the element to change the img src.

Here's a sample of the HTML:

<li class="rollover-child grid-item-2">
    <a href="#">
        <img src="img/copy/file.jpg" width="231" height="130" />
        <span class="gl-grid-text">
            <span class="gl-grid-title">Book!</span>
            <span class="gl-grid-sub-text">View upcoming events</span>
            <span class="gl-grid-arrow">&gt;</span>
        </span>
    </a>
</li>

There are also some list items which don't have an anchor but still need the rollover effect, eg

<li class="rollover-child>
    <img src="img/copy/file.jpg" width="231" height="130" />
</li>

The jQuery I was trying was this:

$(".rollover-child").hover(function() {
    $('img', this).attr("src", $(this).attr("src").split(".").join("-rollover."));
}, function() {
    $('img', this).attr("src", $(this).attr("src").split("-rollover.").join("."));
});

but I can't get it to work at all. I've tried variations with find and children and siblings but I must be doing something wrong.

Any help hugely appreciated.

Cheers, Alex

Upvotes: 1

Views: 3188

Answers (2)

Sushanth --
Sushanth --

Reputation: 55750

In this case $(this) corresponds to to <li class="rollover-child> and you are trying to access the $(this).attr("src") which is wrong .. You need to target the image here.

Try this

 $(".rollover-child").hover(function() {
    $('img', this).attr("src", $(this).find('img').attr("src").split(".").join("-rollover."));
}, function() {
    $('img', this).attr("src", $(this).find('img').attr("src").split("-rollover.").join("."));
});  

Upvotes: 0

Engineer
Engineer

Reputation: 48793

Do like this:

$(".rollover-child").hover(function() {
    $('img', this).attr("src", function(index, currentAttributeValue){
       return currentAttributeValue.split(".").join("-rollover.");
    });
}, function() {
    $('img', this).attr("src", function(index, currentAttributeValue){
       return currentAttributeValue.split("-rollover.").join(".");
    });
});

See .attr( attributeName, function(index, attr) )

Upvotes: 1

Related Questions