Link to home
Start Free TrialLog in
Avatar of Aurelian Constantin
Aurelian ConstantinFlag for Romania

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:

<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>

Open in new window


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>

Open in new window


Thank you for your time.
Avatar of M. Tariq
M. Tariq
Flag of Oman image

Actually the first piece of code is working fine, however setTimeout is not ignored, instead on click the browser redirects to another page.
for testing purposes add [return false;] after setTimeout.
Avatar of Aurelian Constantin

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.
ASKER CERTIFIED SOLUTION
Avatar of M. Tariq
M. Tariq
Flag of Oman image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thank you!