0

I have one larger image with two smaller thumbnails beneath it - Marked up as follows:

<img src="../images/image.jpg" class="left main" alt="main image" /> 
<img src="../images/image2-thumb.jpg" class="left mainthumb" alt="image two" /> 
<img src="../images/image3-thumb.jpg" class="left thumb mainthumb" alt="image three" />

I would like when image2-thumb or image3-thumb is hovered over for it to change image.jpg to the hovered images src BUT without the -thumb.

so if i hover over image2-thumb.jpg then image.jpg becomes image2.jpg and so on. Then on mouseout I would like it to revert back to its original src.

I'm using the following javascript to currently do this but on click:

$(function () {
    $('.mainthumb').click(function () {
        $('.main').attr('src', this.src.replace('-thumb', ''))
    });
});

I'd like to change this to hover but not sure how.

Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
John
  • 989
  • 2
  • 16
  • 29
  • This is your previous question + the accepted answer. – Ram Jan 30 '14 at 14:38
  • 1
    dude, learn `javascript/jQuery` or else you'll just copy/paste code all the time... your last answer question just swaps click with mouseover – Phil Jan 30 '14 at 14:39

5 Answers5

1

Use .hover()

$(function () {
    $('.mainthumb').hover(function () {
        $('.main').prop('src', this.src.replace('-thumb', ''));
    }, function () {
        $('.main').prop('src', '../images/image.jpg');
    }
});

and Use .prop() instead of .attr()

Read .prop() vs .attr()

Community
  • 1
  • 1
Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
1

Simplest way to do this without jQuery using pure JS.

Something like this

<img src="first.png" onmouseover="this.src='second.jpg';"
        onmouseout="this.src='first-or-other-image.png'">

Maybe not very beautiful but works properly

Sergey Pekar
  • 8,555
  • 7
  • 47
  • 54
0
$('.mainthumb').mouseenter(function () {
    // Do your stuff.
});

$('.mainthumb').mouseleave(function () {
    // Do your stuff.    
});

Also see the .hover() documentation.

timmkrause
  • 3,367
  • 4
  • 32
  • 59
0

I would do this with .hover() with callbacks

$('.mainthumb').hover(function () {
      // change the src        
}, function () {
      // change back the src 
});
Praveen
  • 55,303
  • 33
  • 133
  • 164
0

Add the data attribute to the first image to store the original file pointer ("image.jpg") like this:

<img src="../images/image.jpg" data-original="../images/image.jpg" class="left main" alt="main image" /> 

And then add this to your javascript:

$(function () {
    $('.mainthumb').hover(function () {
        $('.main').attr('src', this.src.replace('-thumb', ''))
    }, function() {
        var main = $('.main');
        main.attr('src', main.attr('data-original'));
    });
});
martin
  • 56
  • 1
  • 5