I am facing an issue with my application where sometimes when a user clicks on a div
element, the expected event does not get triggered (~1/10 times). It's puzzling because other times it works perfectly fine. Here is a concise code snippet that replicates this problem:
<html>
<head>
<style type="text/css">
.links:hover{
text-decoration: underline;
cursor: pointer;
}
</style>
</head>
<body>
<span id="init_panel" style="visibility:visible; position:absolute; left:0px; top:0px;"></span>
<script type="text/javascript">
function init_match(){
alert("in init_match()");
//...
}
var flag=true;
function loop(){
if (flag){
var div = document.getElementById("init_panel");
var HTML = "<div class='links' onclick='init_match();'><font color='black'><b>new match!</b></font></div><br />";
if (div.innerHTML!=HTML){
div.innerHTML=HTML;
}
setTimeout(loop, 1000);
}
else{
div.innerHTML="";
}
}
loop();
</script>
</body>
</html>
I need to update the content of multiple divs and their corresponding links using JavaScript, hence the requirement for similar code. Any insight on how to prevent these event failures will be greatly appreciated!
Additional information:
I have also included the following JavaScript code:
document.onclick = my_handler;
function my_handler() {
alert("the document was clicked!");
}
Interestingly, when the div onclick fails, this document onclick also fails. I aim to update div contents without encountering issues with their onclick events.
The most recent version of the jsfiddle demonstrating this bug can be found at:
http://jsfiddle.net/grSDs/3/
The success and failure rates seem to vary across different browsers and when running directly versus through the jsfiddle interface, with success rates ranging from ~90% to ~0%.