SitePoint Sponsor

User Tag List

Results 1 to 2 of 2

Thread: Change the color by setTimeout

Hybrid View

  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
    Grüße aus'm Pott
    SitePoint Award Recipient Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    2,485
    Mentioned
    40 Post(s)
    Tagged
    3 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
    How well do you know your JavaScript from your jQuery?
    Check out SitePoint's latest JavaScript challenge


    My blog

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
  •