9

how do I keep calling a function on mouseover while the mouse is hovered over an html element

Example:

<script>
    function a() {
        "special code hear"
    }
</script>
<div onmouseover( 'a()')>&nbsp;</div>

How can I keep calling the function a while the mouse is hovered over the div instead of having it call the function once.

Arturs
  • 1,258
  • 5
  • 21
  • 28
Mister Joe
  • 135
  • 1
  • 2
  • 6

8 Answers8

11

Events don't repeat automatically. You can use a timer to repeat the command while the mouse is over, but don't forget to stop the timer at the onmouseout event. You'll need a variable outside of the functions to track the timer so it can be cancelled, which is why we have var repeater declared separately.

<script>
  var repeater;

  function a() ...
</script>

<div onmouseover="repeater=setInterval(a(), 100);" onmouseout="clearInterval(repeater);"></div>
Lathejockey81
  • 1,198
  • 7
  • 8
4

Here is one possible solution using setTimeout (DEMO HERE), it will be repeated every second:

HTML CODE:

<div id='div'>test</div>

JS code :

<script>
 document.getElementById('div').onmouseover=function(){a();};

 function a(){

   //some code here

   setTimeout(a,1000);

  }
</script>
MSeifert
  • 145,886
  • 38
  • 333
  • 352
Charaf JRA
  • 8,249
  • 1
  • 34
  • 44
1

TRY THIS FIDDLE

http://jsfiddle.net/C4AVg/

var pee = '';
$('#poop').mouseover(function(){

              pee =  setInterval(function() {
      // Do something every 5 seconds
                   alert('hi');
}, 1000);
});
    $('#poop').mouseout(function() {
        clearInterval(pee);
});
Community
  • 1
  • 1
alex
  • 545
  • 2
  • 6
  • 18
1

As others already mentioned calling a function repeatedly can be achieved using setInterval and stopping it can be done using clearInterval.

In case you're looking for a general solution you could use something like this:

function repeatWhileMouseOver(element, action, milliseconds) {
    var interval = null;
    element.addEventListener('mouseover', function () {
        interval = setInterval(action, milliseconds);
    });

    element.addEventListener('mouseout', function () {
        clearInterval(interval);
    });
}

This starts the interval when the mouse is over the element and will call the action function every milliseconds. When the mouse leaves the element the repeated action will be stopped (until you hover the element again).

Just to show a simple application that counts the accumulated (complete) seconds you hovered an element:

function repeatWhileMouseOver(element, action, time) {
    var interval = null;
    element.addEventListener('mouseover', function() {
        interval = setInterval(action, time);
    });

    element.addEventListener('mouseout', function() {
        clearInterval(interval);
    });
}

var counter = 1;
function count() {
    console.log(counter++);
}
repeatWhileMouseOver(document.getElementById('over'), count, 1000);
#over {
  border: 1px solid black;
}
<span id="over">Hover me (at least one second)!</span>

When you run the snippet note that it stops counting when you leave the element, but it resumes counting when you hover it again.

Maybe important to note that mouseout could also be replaced with mouseleave and similarly for mouseover and mouseenter. They will behave different if the element you attach the handler to has child elements.


Just a note about compatibility:

  • addEventListener is not supported in Internet Explorer 8 and before (see this Q+A for workarounds).
  • The mouseenter and/or mouseleave event are not supported (or supported correctly) in several old browsers. Check the notes about compatibility in case you have to support these (see for example this Q+A).
MSeifert
  • 145,886
  • 38
  • 333
  • 352
0

You should use setInterval() function here...

it also gives you the power to call the function in whatever time interval you desire like: setInterval("a()",1000); here the time is 1/1000 of a second so 1000 means 1 second you can put this setInterval function in any function say b() and call the b() function from the div tag:

<div onmouseover="b()">
Charaf JRA
  • 8,249
  • 1
  • 34
  • 44
Nawed Shaikh
  • 419
  • 5
  • 22
0
<script type="text/javascript">
var tId = null,
    time = 100;
$( '#test' ).hover(
    function( event ) {
        tId = setTimeout( function() {

        }, time);
    },
    function( event ) {
        clearTimeout( tId );
    }
)
</script>
<div id="test">test</div>
Yuan Zhaohao
  • 574
  • 5
  • 4
0
//
// try the timer factory
//
function timer ( callbacks, delay, fireNTimes ) {

    timer._cb ||
    ( timer._cb = function () { return true; } );

    return (function ( callbacks, delay, fireNTimes ) {

        var
            un,
            timerState = {
                'current-count' : 0,
                'delay'         : Math.abs( parseFloat( delay ) )    || 1000,
                'repeat-count'  : Math.abs( parseInt( fireNTimes ) ) || Number.POSITIVE_INFINITY,
                'running'       : false,
                'interval'      : un
            },

            callback = {
                onTimer: callbacks.onTimer || timer._cb,
                onStart: callbacks.onStart || timer._cb,
                onStop : callbacks.onStop  || timer._cb,
                onEnd  : callbacks.onEnd   || timer._cb
            };

        return {

            ctx: this,

            startargs: [],

            start: function ( /* callbacks_context, ...params */ ) {

                var
                    that = this,
                    args = Array.prototype.slice.call( arguments, 1 );

                ( arguments[0] !== un ) && ( this.ctx = arguments[0] );
                ( args.length  != 0 )   && ( this.startargs = args   );

                this.running() || (
                    timerState.running = true,
                    callback.onStart.apply( this.ctx, this.startargs ),
                    timerState['current-count'] += 1,
                    callback.onTimer.apply( this.ctx, this.startargs ),
                    ( timerState['current-count'] == timerState['repeat-count'] ) &&
                      (
                        callback.onEnd.apply( this.ctx, this.startargs ),
                        ( timerState["current-count"] = +( timerState.running = false ) ), true
                      ) ||
                    ( timerState.interval =
                        window.setInterval( function () {
                                timerState['current-count'] += 1;
                                callback.onTimer.apply( that.ctx, that.startargs );
                                ( timerState['current-count'] == timerState['repeat-count'] ) &&
                                that.reset() &&
                                callback.onEnd.apply( that.ctx, that.startargs );
                            }, timerState.delay
                        )
                    )
                );
                return this;
            },
            stop: function () {

                this.running() &&
                (
                  window.clearInterval( timerState.interval ),
                  timerState.interval = un,
                  timerState.running  = false,
                  callback.onStop.apply( this.ctx, this.startargs )
                );
                return this;
            },
            reset: function () {
                return this.running() &&
                ( ! ( timerState["current-count"] = +( timerState.running = false ) ) ) &&
                ( window.clearInterval( timerState.interval ), true ) &&
                ( ( timerState.interval = un ), this );
            },
            currentCount: function () {
                return timerState['current-count'];
            },
            delay: function () {
                return timerState.delay;
            },
            repeatCount: function () {
                return timerState['repeat-count'];
            },
            running: function () {
                return timerState.running;
            }
        };

    })( callbacks, delay, fireNTimes );

}

var
    tm = timer(
               {
                onStart : function () { console.log( 'start:', 'this === ', this, arguments ); },
                onTimer : function () { console.log( 'timer:', 'this === ', this, arguments ); },
                onEnd   : function () { console.log( 'done:',  'this === ', this, arguments ); },
                onStop  : function () { console.log( 'pause:', 'this === ', this, arguments ); }
               },
               2000
         ),
    el = document.getElementById('btn1'),
    o  = { p1:'info' };

el.onmouseover = function () { tm.start( el, o ); };
el.onmouseout  = function () { tm.stop(); };

//
//
//  start: this === <button id="btn1"> [Object { p1="info"}]
//  timer: this === <button id="btn1"> [Object { p1="info"}]
//  timer: this === <button id="btn1"> [Object { p1="info"}]
//  timer: this === <button id="btn1"> [Object { p1="info"}]
//  pause: this === <button id="btn1"> [Object { p1="info"}]
//
//    etc...
//
//
public override
  • 974
  • 8
  • 17
0

I think what you're looking for is actually the onmousemove event, it's a cleaner way to access the event object while you hover some element.

<script>
    function a() {
        "special code hear"
    }
</script>

<div onmousemove( 'a()')>&nbsp;</div>

onmousemove event is called while you're hovering the element, check this example from W3 School.

And to understand more about this event, Mozilla docs covers much info about it.

Lucas Andrade
  • 4,315
  • 5
  • 29
  • 50