0

When I mouseover .thumb I want the src to be replaced by hello.gif and when I mouseout I want the src to revert back to the original value. The first part is easy but for the second part I don't know how to "remember" the original src value.

$('.thumb').mouseover(function() {
    current_src = $(this).attr("src");
    $(this).attr("src", basepath+"_img/hello.gif");
});

$('.thumb').mouseout(function() {
    $(this).attr("src", ???);
});
1
  • 1
    Is there any reason you can't use CSS psuedo classes? You could use :hover, specifically. Commented Feb 25, 2012 at 14:16

4 Answers 4

3
$('.thumb').mouseover(function() {
    $(this).data('prev_src', $(this).attr('src')).attr("src", basepath+"_img/hello.gif");
});

$('.thumb').mouseout(function() {
    $(this).attr("src", $(this).data('prev_src'));
});
Sign up to request clarification or add additional context in comments.

Comments

1

You could use the data method of jquery

http://api.jquery.com/jQuery.data/

$('.thumb').mouseover(function() {
    // save the original src here
    $(this).data('src', $(this).attr("src"));
    $(this).attr("src", basepath+"_img/hello.gif");
});

$('.thumb').mouseout(function() {
    $(this).attr("src", $(this).data('src'));
});

http://jsfiddle.net/StGdt/

Comments

1

I wrote a small jQuery plugin for this:

(function( $ ) {
    jQuery.fn.toggleSource = function(img){
        return this.each(function() {
        if(this.tagName.toLowerCase() != 'img') return;
            var $this = $(this);
            var orig = $this.attr('src');
            $this.mouseover(function(){
                $this.attr('src',img);
            });
            $this.mouseout(function(){
                $this.attr('src', orig);
            });
        });
    }
})(jQuery);

You can use it this way:

$('.thumb').toggleSource('http://my.site/my.img');

Comments

0

This is much better

$('.hover').mouseover(function() {
    $(this).data('src', $(this).attr("src"));
    $(this).attr("src", $(this).attr("data-hover"));
});

$('.hover').mouseout(function() {
    $(this).attr("src", $(this).data('src'));
});

Just put data-hover on imagen

<img src="http://placehold.it/300x200" alt="" class="hover" data-hover="http://placehold.it/350x250" />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.