简体   繁体   中英

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>

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> 

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> 

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);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM