atho
atho

Reputation: 133

Increment number every second as long as the mouse is on div

So here is a thing. I want number to be incremented by one each second while mouse pointer is on div element, but somehow it doesn't and I don't know where the problem is.

JS:

var num = 1;
var count = setInterval(
    function(){
        $("div").mouseover(
            function(){
                document.getElementById("myID").innerHTML = num;
                num++;
            }
        );
    }
,1000);

HTML:

<p id="myID"></p>
<div style="height:100px;width:100px;background-color:#3A5795;"></div>

Upvotes: 2

Views: 2691

Answers (3)

blex
blex

Reputation: 25659

You may try this:

var num = -1, count;

$('div').hover(startCounter, stopCounter);

function startCounter(){
    $("#myID").html( ++num );
    count = setTimeout(startCounter, 1000);
}

function stopCounter() {
    clearInterval(count);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p id="myID">Hover the box to start counting.</p>
<div style="height:100px;width:100px;background-color:#3A5795;"></div>

Upvotes: 2

Thalsan
Thalsan

Reputation: 5700

Set the interval on mouseover and clear the interval on mouseout. Make sure to declare the interval so you can stop it.

var count = 0;
$('body').on('mouseover', 'div', function () {
    inc = setInterval(function () {
        count++;
        $('#myID').text(count);
    }, 1000);
}).on('mouseout', 'div', function () {
    clearInterval(inc);
});

Upvotes: 0

Ga&#235;l Barbin
Ga&#235;l Barbin

Reputation: 3919

You are adding the same event listener each second. I do not think that is what you want.
You have also to clearInterval when mouse is not on the div.

var num = 1;
$("div").mouseover(
  function(){

    incInterval= setInterval(function(){
      document.getElementById("myID").innerHTML = num;      
      num++;

    },1000);
    
  }
);
$("div").mouseout(
  function(){

    clearInterval(incInterval);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="height:100px;width:100px;background-color:#3A5795;"></div>

<p id="myID"></p>

Upvotes: 2

Related Questions