Reputation: 21
I have been trying out a function where when a mouse hovers over the photo it changes. Is there a way to animate this change?
<img src='./images/rocks.jpg' onmouseover="this.src='./images/seasky.jpg';"
onmouseout="this.src='./images/rocks.jpg';" />
Upvotes: 1
Views: 2804
Reputation: 65808
First, inline HTML event attributes (i.e. onmouseover, onmouseout, etc.) should not be used. The use of these kinds of attributes persists today because sites like W3 Schools still show them and millions upon millions of inexperienced developers just copy/paste code that they've seen somewhere else and because it seems to work, they don't think twice about it. In fact, there are many reasons why these attributes should die the abrupt death they deserve.
Now, to your specific question, if you want a transition effect, you'll need to use CSS to set it up. And, it's probably best done by using background images of a div
element, rather than altering the src
of an img
element.
See the comments for details:
/* Separate your event handling code from your markup */
// Get a reference to the element
let fancy = document.querySelector(".fancyImage");
// Set up the mouseover event handler
fancy.addEventListener("mouseover", function(){
this.classList.add("go"); // Change to the Go image
this.classList.remove("stop"); // Remove the Stop image
});
fancy.addEventListener("mouseout", function(){
this.classList.add("stop"); // Change to the Stop image
this.classList.remove("go"); // Remove the Go image
});
/* Use CSS for all styling and layout */
.fancyImage {
/* Set up a transition for all property changes that takes place over 1 second */
transition:all 1s;
/* Set the size of the div, otherwise it will collapse because there's no content
in its foreground */
width:200px;
height:160px;
}
/* The element starts off with the stop class hard-coded, so it starts with this image */
.fancyImage.stop {
background: url("https://img.favpng.com/15/11/21/stop-sign-traffic-sign-clip-art-png-favpng-YVm6TAKXcApfNG5qQLT1Axke0.jpg");
/* Make the image fit into the element */
background-size:contain;
background-repeat:no-repeat;
}
/* This class gets dynamically added on mouse over */
.fancyImage.go {
background: url("https://theblogreaders.com/wp-content/uploads/2015/12/Go-298x300.gif");
background-size:contain;
background-repeat:no-repeat;
}
<!-- Don't use HTML event attributes or self-terminating tags.
See how much cleaner the HTML is now? -->
<div class="fancyImage stop">
Upvotes: 1