My latest project involves coding a block that displays an image on an HTML page, with a new image appearing each time the user hovers over it. However, there's a glitch in my code that causes the images to flicker erratically if the mouse is moved even slightly inside the image, as the mouseover event isn't properly handled. Additionally, I encountered an issue where I had to include an empty placeholder at the 0 index in the array for the code to work as intended.
Instead of solely focusing on finding a solution, I am more interested in understanding the problem and how to approach it correctly.
<div id="myImage">
<img id="theImg" src="whatever.png" alt="yay" height="42" width="42">
</div>
<script>
imgs = ['placeholder','house','piggy','food'];
$('#myImage').mouseenter(function(){
$( "#theImg" ).remove();
var rand = Math.floor(Math.random()*3)+1;
$('#myImage').append('<img id="theImg" src=' + imgs[rand] +'.png' + '>');
console.log(imgs[rand]);
});
</script>