Aurelian Constantin
asked on
Javascript setTimeout problem
I wanted to change the background color of a DIV (id=appdtic) on every click on all links; the bg-color should stay yellow for 3 seconds, and then the browser should load the link provided. Here's the code that does NOT work:
The alerts inside the functions are for testing purposes. But, this doesn't work as expected. For me, it seems that setTimeout is ignored. What is wrong in the code?
For comparison, here is another code that works, although id does something else (it waits 3 seconds before actually submitting the form):
Yes, the button is not of a submit type, and is outside the form, so to circumvent the default event of the form.
Thank you for your time.
<div id="appdtic">appdtic</div>
<div><a href="tst1.html">first link</a></div>
<div><a href="tst2.html">second link</a></div>
<div><a href="tst3.html">third link</a></div>
<div><a href="tst4.html">fourth link</a></div>
<script>
function dofunc() {
alert('func alert!');
}
var elements = document.getElementsByTagName('a');
for(var i = 0, len = elements.length; i < len; i++) {
elements[i].onclick = function () {
document.getElementById('appdtic').style.backgroundColor='yellow';
alert('some alert!');
setTimeout(dofunc, 3000);
}
}
</script>
The alerts inside the functions are for testing purposes. But, this doesn't work as expected. For me, it seems that setTimeout is ignored. What is wrong in the code?
For comparison, here is another code that works, although id does something else (it waits 3 seconds before actually submitting the form):
Yes, the button is not of a submit type, and is outside the form, so to circumvent the default event of the form.
<form name="formular" id="formular" method="post" action="test2.php">
</form>
<input type="button" value="send" id="submit">
<script>
function submitForm() {
document.getElementById("formular").submit()
}
document.getElementById('submit').onclick = function() {
setTimeout(submitForm, 3000);
}
</script>
Thank you for your time.
ASKER
@Mohammed Tariq
Thank you for your early reply!
I added [return false;] after setTimeout, but it does not follow the link any more, although it waits 3 seconds before executing dofunc.
Thank you for your early reply!
I added [return false;] after setTimeout, but it does not follow the link any more, although it waits 3 seconds before executing dofunc.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thank you!
for testing purposes add [return false;] after setTimeout.