views:

151

answers:

1

Hi, I have made this piece of code that makes a roll hover effect on any image you add the class 'simplehover' to it :

    //rollover effect on links 
    $(".simplehover").mouseover(function () {
        $(this).attr("src", $(this).attr("src").replace("-off.", "-on."));
    }).mouseout(function () {
        $(this).attr("src", $(this).attr("src").replace("-on.", "-off."));
    });

<img src="slogan.gif" class="simplehover" />

Im trying to get it work if you add the class 'simplehover' to the surrounding element : . (especially usefull for ASP.net asp:HyperLink tag which automatically generate the IMG tag inside the hyperlink.

<a href="#" class="simplehover"> <img src="slogan.gif" /> </a>

If I change my selector for : $(".simplehover img") , it will work, however it no longer works in senario #1.

I tried this, but no luck:

$(".simplehover").mouseover(function () {
if ($(this).has('img')) { $(this) = $(this).children(); }
...

Anyone can figure this out?

+2  A: 

You can refactor using a combination of the hover() method and the multiple selector.

$("a.simplehover img, img.simplehover").hover(function () {
    $(this).attr("src", $(this).attr("src").replace("-off.", "-on."));
}, function() {
    $(this).attr("src", $(this).attr("src").replace("-on.", "-off."));
});

<img src="slogan.gif" class="simplehover" />
hunter
+1 - More efficient than mine.
patrick dw
Works perfectly! Thanks!
Etienne Dupuis
you need to replace the url ending (on to off and vice versa), try this: `$("a.simplehover img, img.simplehover").hover(function () { $(this).attr( "src", function(i, attr){ return attr.replace("-off.", "-on."); }) }, function() { $(this).attr( "src", function(i, attr){ return attr.replace("-on.", "-off."); }) });`
fudgey