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?
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?
 
    
     
    
    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";
}
 
    
    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;}
 
    
    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');
});
 
    
    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>
