user1091856
user1091856

Reputation: 3158

JQuery: Dynamic image replace on hover?

I want a Jquery function that takes a img element, and when it is hovered, it replaces the img like this: myimage.png replaces to myimage2.png

This is what I came up with but it's not working:

        $("#menu img").hover(function(){
        var split = $(this).attr("src").split(".png");
        $(this).attr("src", split[0]+"2.png");
    }, function(){
        var split = $(this).attr("src").split(".png");
        $(this).attr("src", split[0]+".png");
    });

I'm sure the veterans can come up with a much better approach, so please.

Upvotes: 0

Views: 1561

Answers (2)

powerbuoy
powerbuoy

Reputation: 12838

Your second function won't change the src attribute at all as all you're doing is removing the ".png" bit and then re-adding it. You'll need to remove the "2" as well. I guess you could change split('.png') to split('2.png').

But in most cases CSS is a much better solution for this. Unless you actually want to display images (like in a gallery) you can set background-images on other elements and swap them on hover. Even better, use an image sprite to keep HTTP requests down to a minimum:

#menu a {
    background: url(menu.png) no-repeat; /* menu.png contains ALL the images used in the menu */
    display: block;
    width: 80px;
    height: 20px;
    text-indent: -1000000px; /* Remove text */
}

#menu a:hover {
    background-position: left -20px;
}

Upvotes: 2

Jonathan Payne
Jonathan Payne

Reputation: 2223

Hope this helps, let me know if you have any questions.

jsFiddle( http://jsfiddle.net/ZWxEg/12/ )

<script type='text/javascript'>

    var split = new Array();

    split[0] = "http://www.google.com/logos/2012/sundback12-hp.jpg";
    split[1] = "http://www.google.com/logos/2012/sovereignty12_hp.jpg";

    $(document).ready(function()
    {
        $(".button").hover( function ()
        {
             $(this).attr( "src" , split[1] );
        },
        function ()
        {
             $(this).attr( "src" , split[0] );
        });
    });
</script>

<div id="menu">
    <img src="http://www.google.com/logos/2012/sundback12-hp.jpg" alt="My button" class="button" />
</div>
​

Upvotes: 0

Related Questions