Search code examples
javascriptonclicklistener

Clock is Always Displaying


Hi there guys I am trying to create a clock to where it will only show when a certain div is click on. But what seems to be happening is that the clock is always showing and I have no clue why this is happening. Below is my code that I have tried so far.

<!DOCTYPE html>
<html>
<head>
    <title>JS Clock tuts</title>
</head>
<body>
    <div id="stop">CLICK HERE</div>
    <script>

    var get = document.getElementById("stop");
    get.addEventListener("click", showTime())

        function showTime() {
            var now = new Date();
            var h = now.getHours();
            var m = now.getMinutes();
            var s = now.getSeconds();
            var state = "AM";

            s = (s < 10) ? "0" + s : s;
            m = (m < 10) ? "0" + m : m;

            if (h > 12) 
            {
                h = h - 12;
                state = "PM";
            }

            if (h == 0) 
            {
            h = 12;
            }
            var time = h + ":" + m +":" + s + " " + state;
            document.getElementById("stop").innerHTML = time;
            setTimeout(showTime, 0);
        }

    </script>
</body>
</html>

Solution

  • you want show or hide like this?

    document.getElementById("show").addEventListener('click', function() {
      document.getElementById("clock").style.visibility = "visible";
      showTime();
    });
    document.getElementById("hide").addEventListener('click', function() {
      document.getElementById("clock").style.visibility = "hidden";
    });
    
    
    function showTime() {
      var now = new Date();
      var h = now.getHours();
      var m = now.getMinutes();
      var s = now.getSeconds();
      var state = "AM";
    
      s = (s < 10) ? "0" + s : s;
      m = (m < 10) ? "0" + m : m;
    
      if(h > 12) {
        h = h - 12;
        state = "PM";
      }
    
      if(h == 0) {
        h = 12;
      }
      var time = h + ":" + m + ":" + s + " " + state;
      document.getElementById("clock").innerHTML = time;
      setTimeout(showTime, 0);
    }
    #clock{visibility:hidden}
    #show,#hide{cursor:pointer}
    <div id="show">show</div>
    <div id="hide">hide</div>
    <div id="clock"></div>