An "if mouseover" or a "do while mouseover" in JavaScript/jQuery
Asked Answered
P

5

14

Is there a JavaScript or jQuery solution to run a function repeatedly (after setTimeout) while the mouse is over a DOM object? Otherwise said, is there a JavaScript "do while mouseover" (or "if mouseover")?

    $('someObject').bind('mouseover', function() {

        //Do the following while mouseover 
        $('someOtherObject').css('margin-left',adjustedLeft + 'px');
        setTimeout(/*do it again*/,25);

    });
Proprioceptor answered 19/10, 2010 at 7:52 Comment(0)
T
41
$('someObject').on('mouseenter', function() {
    this.iid = setInterval(function() {
       // do something           
    }, 25);
}).on('mouseleave', function(){
    this.iid && clearInterval(this.iid);
});

Example Look here

Telescopy answered 19/10, 2010 at 7:58 Comment(3)
i use new bind style of jQueryStack
Is it possible to execute that event once per hover? Currently it will be executed multiple times until the element is hovered. I want to do that just once.Yellowhammer
What is the point of having this.iid && clearInterval(this.iid) wouldn't clearInterval suffice?Falsity
M
0

I would solve this issue using the onmouseout event. Start whatever you intended to do while the mouse is over the specified component on the mouseover event. When onmouseout event occurs i would stop it.

Manny answered 19/10, 2010 at 7:57 Comment(0)
S
0

i use new bind style of jQuery.

$(el).bind({
'mouseenter': function(){console.log('Mouse over');}, 
'mouseleave': function(){console.log('Mouse leave');}
});
Stack answered 14/6, 2011 at 18:14 Comment(0)
E
0

I know this is kind of old, but I think the proper function is already in JavaScript, onmousemove does just that.

Educable answered 6/12, 2013 at 16:32 Comment(0)
A
0
OBJ.addEventListener("mouseenter", function() {
  focus=true;
});
OBJ.addEventListener("mouseleave", function() {
  focus=false;
});

Just in case you don't want to use jquery you can use this :)

Allsun answered 2/1, 2019 at 7:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.