I put an image in a div. When I move the mouse into the div, the image should decrease by 5% every second. I’ve done this script but nothing happens.
document.addEventListener("DOMContentLoaded", (event) => {
const element = document.getElementsByTagName("footer")[0];
const div = element.getElementsByTagName("div")[0];
var urlImg = "https://www.coding-academy.fr/wp-content/uploads/2017/10/CODING_LOGO_CMJN.png";
var imagejavascript = document.createElement("img");
imagejavascript.src = urlImg;
imagejavascript.style.width = "100%";
imagejavascript.style.height = "100%";
div.appendChild(imagejavascript);
const img = div.getElementsByTagName("img")[0];
var isOnDiv = false;
var currentHeight = 100;
div.addEventListener("mouseenter", function() {
if (isOnDiv) return;
isOnDiv = true;
var intervalId = setInterval(function() {
currentHeight -= 5;
img.style.height = currentHeight + "%";
if (currentHeight <= 0) {
clearInterval(intervalId);
setTimeout(function() {
isOnDiv = false;
currentHeight = 100;
img.style.height = "100%";
}, 1000);
}
}, 1000);
});
div.addEventListener("click", function() {
div.removeChild(img);
});
});
<footer>
<div></div>
</footer>
I’m trying to find a way to reduce the image size by 5% every second I enter the mouse in the div.
3
Answers
There’s a few issues here:
isOnDiv
is alwaysfalse
. The condition in yourmouseenter
handler immediately checks for atrue
value, which is never found, so returns before any logic runs.height
andwidth
of theimg
to100%
. A change to a single one of them will have no effect. You need to set one of the values and have the image sale dynamically as you then scale it down.mouseenter
andmouseleave
event handlers to start and end the interval, respetively.Here’s a working example with the above changes made:
Setting height by percentage only works when the parent element has a fixed height. In your case, there is no styling on the parent
div
, so the width and height styling of your image does not work.One way to fix is to first render the image in your
div
, and then set the height and width of yourdiv
to its current calculated dimensions. You can put the following lines of code after inserting the image to the div:Your code was almost correct. Here is another way by not changing much your code. Your attempt to use the flag isOnDiv is not correct you should use on mouseleave event.