SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Member
    Join Date
    Dec 2012
    Posts
    12
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Change the color by setTimeout

    What am I doing wrong that you click the "click" the color changes only once?
    Code:
    <p id="klik">Click</p>
    <div id="block">example text change color</div>
    
    <script>
    document.getElementById('klik').onclick=function(){
      setTimeout('ppp()', 1000);  
    }
    function ppp() {
          var index = Math.round(Math.random() * 3);
          var ColorValue = "green";
          if(index == 1) ColorValue = "red";
          if(index == 2) ColorValue = "lime";
          if(index == 3) ColorValue = "yellow";
          document.getElementById("block").setAttribute("style","color:" + ColorValue);  
    } 
    </script>

  2. #2
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    6,055
    Mentioned
    219 Post(s)
    Tagged
    12 Thread(s)
    Hi there,

    To have an action repeat indefinitely use setInterval()

    Code JavaScript:
    document.getElementById('klik').onclick=function(){
      setInterval('ppp()', 1000);  
    }

    This'll work.

    You can read more about the differences here: http://javascript.info/tutorial/settimeout-setinterval


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •