Cuckoo Cuckoo - 2 months ago 10
Javascript Question

Stop onmouseenter repeatedly firing in Chrome and Firefox

I'm having a nightmare trying to figure this out. The onmouseenter even keeps firing ever after the mouse enters a div with the event, every time the mouse moves it triggers the funciton. It works fine in IE, just not Chrome or FF. Here is a live version of code : http://infinitedv.co.uk/rantest/random_test_2.1.html

I've not preloaded the images, so it may take a few passes to see all the images. Thank you in advance for any help. I've tried using a timeout, but that didn't really pan out, and was messy.



var ranNum, result_10, resultFloor, piccy, audio, a, divVar;

function myFunction(a) {
if (a === 0) {
divVar = "demo";
}
else if (a === 1) {
divVar = "demo1";
}
else if (a === 2) {
divVar = "demo2";
}
ranNum = Math.random();
result_10 = (ranNum * 5) + 1;
resultFloor = Math.floor(result_10);
piccy = "<img src=\"random_images/" + resultFloor + ".gif\" />";
document.getElementById(divVar).innerHTML = piccy;
}

<div id="container">
<div id="demo" onmouseenter="myFunction(0)">This</div>
<div id="demo1" onmouseenter="myFunction(1)">This</div>
<div id="demo2" onmouseenter="myFunction(2)">This</div>
<div>Will's Imagepop test. </div>
<audio id="audio" src="pop.wav" ></audio>
</div>




Answer

Man, really weird. But it is something with the innerHTML of the div. Check this version where it is working with the background image instead of replacing its content.

var ranNum, result_10, resultFloor, piccy, audio, a, divVar;

function myFunction(a) {
    console.log('function called for', a);
	if (a === 0) {
		divVar = "demo";
	}
	else if (a === 1) {
		divVar = "demo1";
	}
	else if (a === 2) {
		divVar = "demo2";
	}
	ranNum = Math.random();
	result_10 = (ranNum * 5) + 1;
	resultFloor = Math.floor(result_10);
	piccy = "<img src=\"random_images/" + resultFloor + ".gif\" />";
	//document.getElementById(divVar).innerHTML = piccy;
        document.getElementById(divVar).style.background = "url(random_images/" + resultFloor + ".gif)";
}
<div id="container">
	<div id="demo" onmouseenter="myFunction(0)">This</div>
    <div id="demo1" onmouseenter="myFunction(1)">This</div>
    <div id="demo2" onmouseenter="myFunction(2)">This</div>
    <div>Will's Imagepop test. </div>
    <audio id="audio" src="pop.wav" ></audio>
</div>