0
<img src="img/image1.png" id="mainimage">

<p><a href="#" id="pet1">Dog</a></p>
<p><a href="#" id="pet2">Cat</a></p>

I am trying to use JavaScript/jQuery so that whenever a user places their mouse over any of the links with the id's pet1 & pet2 it will change the image src of the image with the id of mainimage.

var img = document.getElementById('swap');
document.getElementById('pet1').onmouseover = function(){
    // manipulate the image source here.
    img.src = img.src.replace(/\.jpg/, '-on.jpg');
}

The above JavaScript is a script I found here that seems to have the functionality I am looking for. The only problem is that whenever my mouse is over the link it does not display the image I want. Ok, the question I am looking for is how can I make the image with the source (img/pet1.jpg) appear?

Any help will be appreciated!

Meryovi
  • 6,121
  • 5
  • 42
  • 65

3 Answers3

1

Try this more simply

$(function() {
    $("#pet1")
        .mouseover(function() { 
            var src = 'first image path';
            $("#mainimage").attr("src", src);
        })
        .mouseout(function() {
            var src2 ='Default image path';
            $(this).attr("src", src2;
        });
});

Similllar for second image and for shortening even this you can give a class to every link you want and then by using $(element).each() function and "data" attribute of html5 you can manage it in more cool way

Ali
  • 231
  • 1
  • 4
  • 17
  • Thanks for your reply man! How does this work. I have
  • tags with anchors in them and want to manipulate an images with id="mainimage" The above code was just an expample. Can you explain on how to work with this script?
  • – Abraham Guzman Oct 02 '14 at 13:00