Jack
Jack

Reputation: 753

Counter with jquery

It is a newbie question, I am trying to make a counter using jquery and this the code that I got from a tutorial on youtube, but it does not work.

<!DOCTYPE html>
<html>

<head>
    <script type="text/javascript" src="http//code.jquery.com/jquery- 1.7.1.min.js"></script>
</head>

<body>
    <div id="counter">0</div>
    <script type="text/javascript">
    var counter = 0;

    setinterval("timer()", 1000);

    function timer() {
        counter++;
        $('#counter').text(counter);
    }
    </script>
</body>

</html>

Any idea what is wrong?

Upvotes: 0

Views: 113

Answers (2)

Tushar
Tushar

Reputation: 87203

  1. The function name is setInterval(note capital I) and not setinterval
  2. Also, don't use string as parameter to the setInterval. // Not error, but it is good practice
  3. Also, the URL of jQuery is wrong, contains space in the jquery and version.

    http//code.jquery.com/jquery- 1.7.1.min.js
    //                           ^
    

Demo:

var counter = 0;
setInterval(timer, 1000);

function timer() {
  counter++;
  $('#counter').text(counter);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div id="counter">0</div>

Upvotes: 3

Marcos Brinner
Marcos Brinner

Reputation: 207

try it cause you are using a local variable try to use an global like this an your are using seinterval() that doesn't exists use setInterval() i'am using jquery labery

<div id="counter">0</div>
<script type="text/javascript">

   window.counter = 0;

   setInterval(function(){timer()},1000);

   function timer() {

     window.counter++;

   $('#counter').text(window.counter);

}
<script>

Upvotes: 1

Related Questions