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.

6
  • @FaceOfJock it muste be setInterval() Commented Aug 31, 2013 at 3:39
  • you can do this using setInverval when hover over and cleartimeout when hover out Commented Aug 31, 2013 at 3:40
  • @DipeshParmar he want it to be executed more than one time , not executed after x secondes Commented Aug 31, 2013 at 3:40
  • @FaceOfJock well settimeout will work only once after defined time...where as setInterval keep calling function after specified amount of time... Commented Aug 31, 2013 at 3:40
  • @FaceOfJock Read Here Commented Aug 31, 2013 at 3:41

9 Answers 9

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> 
Sign up to request clarification or add additional context in comments.

Comments

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> 

1 Comment

You can also replace the timeout line with: setTimeout("a", 1000);
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); }); 

1 Comment

he is not using jQuery
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).

Comments

1

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.

Comments

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> 

Comments

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()"> 

1 Comment

Sorry i am using mobile to type so cant put it in right format
0

Here is an example event listener the function fires continuously while the mouse is moving on the target element (const element).

Their are some other mouse events included as well.

<script> document.addEventListener("DOMContentLoaded", function () { function MouseControls() { const element = document.querySelector('.ClassName'); const move = (e) => { console.log('move = (e)', e) } element.addEventListener('mousemove', move, false); // element.addEventListener('mousedown', move, false); // element.addEventListener('mouseup', move, false); // element.addEventListener('mouseleave', move, false); } MouseControls() }); </script> 

Comments

-1
// // 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... // // 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.