Search code examples
javascripttexttimeronmouseover

add stop onmouse over to this simple code


I would like to add a 'onmouseover stop' setting to this piece of code. This is because I plan to write long bits of text and I would like to give the reader a change to stop the text from changing in case they haven't stopped reading.

I have found similar questions but they relate to stopping a marquee from scrolling on mouseover. Ive tried adding the same code that seems to make a marquee stop but it just makes my code stop working all together.

<div id="changeText" ></div>
<script type="text/javascript">
    var text = ["1", "2", "3"];
    var counter = 0;
    var elem = document.getElementById("changeText");
    setInterval(change, 5000);
    function change() {
       elem.innerHTML = text[counter];
       counter++;
       if(counter >= text.length) { counter = 0; }
    }
</script>

Solution

  • You can use clearInterval() and pass the intervalId returned by your setInterval() call on a mouseover event, then restart on mouseout, as shown in the updated sample code below:

    <div onmouseover="stop()" onmouseout="start()" id="changeText" ></div>
    <script type="text/javascript">
    var text = ["1", "2", "3"];
    var counter = 0;
    var elem = document.getElementById("changeText");
    var intervalId;
    start();
    
    function start() {
        intervalId = setInterval(change, 5000);
        function change() {
            elem.innerHTML = text[counter];
            counter++;
            if(counter >= text.length) { counter = 0; }
        }
    }
    
    function stop() {
        clearInterval(intervalId);
    }
    
    </script>