0

I have two images, what I want to happen is that when I hover on the image, the image will change to the second image, and then when I hover on the image again, the image will change to the first image.

How do I do that using JavaScript?

Vaibhav Mule
  • 5,016
  • 4
  • 35
  • 52
cifer
  • 21
  • 1
  • 7
  • 4
    describe what you've done (using code preferably) – A. L Feb 19 '17 at 12:16
  • 4
    Please include the code you've written so far. The more details you provide, the more answers you are likely to receive. Check the [FAQ](http://stackoverflow.com/tour) and [How to ask](http://stackoverflow.com/help/how-to-ask). – Roald Nefs Feb 19 '17 at 12:16
  • 1
    Go through this link [Changing image on hover](http://stackoverflow.com/questions/10886828/changing-image-on-hover) – Deepali Gomashe Feb 19 '17 at 12:23
  • 1
    It's not clear whether you're referring to the tag `` or simply an image. If the latter, then you can just use plain CSS to switch images on hover by changing the background image. See this example: https://jsfiddle.net/hnrjdkut/ – dabadaba Feb 19 '17 at 12:29
  • removed unwanted sentence – Vaibhav Mule Feb 22 '17 at 14:42

4 Answers4

2

This is a Javascript solution. I highly suggest you look into Jquery once you understand the below. In your case you don't seems to need the onmouseout.

HTML

<img src="urImg.png" onmouseover="chgImg(this)" onmouseout="normalImg(this)">

Javascript

function chgImg(x) {
x.src = "newImg.png";
}

function normalImg(x) {
x.src = "urImg.png";
}
0

HTML

<div class="image_container">
 <img src="foo.png" class="first"/>
 <img src="bar.png" class="last"/>
</div>

jQuery

$(".image_container").hover(function(){
  $(this).toggleClass("switch");
});

CSS

.image_container .last{display:none;}
.image_container.switch .last{display:block;}
.image_container.switch .first{display:none;}
CodingKiwi
  • 676
  • 8
  • 22
0

You can do this!

<a href="#" id="name">
    <img title="Hello" src="images/view2.jpg>
</a>


  $('#name img').hover(function() {
   $(this).attr('src', 'images/view1.jpg');
   }, function() {
  $(this).attr('src', 'images/view2.jpg');
});
Myco Claro
  • 475
  • 2
  • 14
0

For anyone who do not want to use Javascript, just HTML, CSS.

You just need create second image with position: absolute; and put it with original image into a div (with position: relative;)

After that, you can use CSS to control opacity of second image when you hover it.

Below is my sample code using TailwindCSS

<div className="relative">
 <img 
    src="/image1.png" 
    className="w-[100px] h-[100px]"/>
 <img 
    src="/image1.png" 
    className="w-[100px] h-[100px] absolute opacity-[0] hover:opacity-[1]"/>
</div>
Phong
  • 1,457
  • 14
  • 16