开发者

jQuery - triggering a regular function call on mousedown

I want a function to be called regularly at a given interval whilst the left mouse button is being held down over a specific开发者_Python百科 element. Is there a simple way of doing this in jQuery or should I use vanilla javascript and setInterval/setTimeout?

Thanks


Here's a jQuery plugin that provides a mousehold event.

http://remysharp.com/2006/12/15/jquery-mousehold-event/

If you go to the demo page and click on one of the arrows to the right of the last input box you'll see how it works.


This is how I would do it:

HTML:

<div id="box"></div>

JavaScript:

var box = $('#box'),
    iv;

function foo() {
    box.append('*');    
}

box.bind('mousedown mouseup', function(e) {
    $(this).toggleClass('hold', e.type === 'mousedown');
});

iv = setInterval(function() {    
    box.hasClass('hold') && foo();
}, 1000);

So you bind a handler to both the mousedown and mouseup events, and set the hold CSS class accordingly. Meanwhile, an independent timer iv will inspect whether or not the hold class is set, and call your function (foo) accordingly.

Live demo: http://jsfiddle.net/simevidas/7CUFE/


jQuery does not provide any function watching support as a result, you could use the vanilla setTimeout function as follows:

var timer;

function functionToRun() {
    // Function code here...
    functionToRun();
}

var inFunction = function() {
    timer = window.setTimeout(functionToRun, intervalToRunFor);
}

var outFunction = function() { 
    window.clearTimeout(timer);
}

$('selector').hover(function() { inFunction, outFunction }


var mouseDown = false;

$('#yourID').bind('click', function() {
    mouseDown = true;
});

$('#yourID').bind('mouseup', function() {
    mouseDown = false;
});

setInterval('checkOut();',5000);

function checkOut() {
   if(mouseDown) alert('mouse is down! Whatup!');
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜