117

I want to be able to fire an event when a user clicks on a button, then holds that click down for 1000 to 1500 ms.

Is there jQuery core functionality or a plugin that already enables this?

Should I roll my own? Where should I start?

Coleman
  • 565
  • 7
  • 15
SnickersAreMyFave
  • 5,047
  • 8
  • 26
  • 24

7 Answers7

181
var timeoutId = 0;

$('#myElement').on('mousedown', function() {
    timeoutId = setTimeout(myFunction, 1000);
}).on('mouseup mouseleave', function() {
    clearTimeout(timeoutId);
});

Edit: correction per AndyE...thanks!

Edit 2: using bind now for two events with same handler per gnarf

Machado
  • 8,965
  • 6
  • 43
  • 46
treeface
  • 13,270
  • 4
  • 51
  • 57
13

Aircoded (but tested on this fiddle)

(function($) {
    function startTrigger(e) {
        var $elem = $(this);
        $elem.data('mouseheld_timeout', setTimeout(function() {
            $elem.trigger('mouseheld');
        }, e.data));
    }

    function stopTrigger() {
        var $elem = $(this);
        clearTimeout($elem.data('mouseheld_timeout'));
    }


    var mouseheld = $.event.special.mouseheld = {
        setup: function(data) {
            // the first binding of a mouseheld event on an element will trigger this
            // lets bind our event handlers
            var $this = $(this);
            $this.bind('mousedown', +data || mouseheld.time, startTrigger);
            $this.bind('mouseleave mouseup', stopTrigger);
        },
        teardown: function() {
            var $this = $(this);
            $this.unbind('mousedown', startTrigger);
            $this.unbind('mouseleave mouseup', stopTrigger);
        },
        time: 750 // default to 750ms
    };
})(jQuery);

// usage
$("div").bind('mouseheld', function(e) {
    console.log('Held', e);
})
gnarf
  • 105,192
  • 25
  • 127
  • 161
9

I made a simple JQuery plugin for this if anyone is interested.

http://plugins.jquery.com/pressAndHold/

Tony Smith
  • 869
  • 1
  • 11
  • 25
  • Nice one. Was able to modify this to detect that an object had been dragged so as to remove a message telling the user to drag the object. – Starfs Oct 13 '16 at 19:12
  • FANTASTIC plugin. Dropped in to my project and bam, works. – Andy Oct 24 '18 at 20:51
  • Your plugin wasn't written for Bootstrap, but works VERY nicely with it! No extra CSS or messing around. Just works. Kudos. – Andy Oct 24 '18 at 20:53
5

Presumably you could kick off a setTimeout call in mousedown, and then cancel it in mouseup (if mouseup happens before your timeout completes).

However, looks like there is a plugin: longclick.

VK Da NINJA
  • 510
  • 7
  • 19
Jacob Mattison
  • 50,258
  • 9
  • 107
  • 126
2
    var _timeoutId = 0;

    var _startHoldEvent = function(e) {
      _timeoutId = setInterval(function() {
         myFunction.call(e.target);
      }, 1000);
    };

    var _stopHoldEvent = function() {
      clearInterval(_timeoutId );
    };

    $('#myElement').on('mousedown', _startHoldEvent).on('mouseup mouseleave', _stopHoldEvent);
kayz1
  • 7,260
  • 3
  • 53
  • 56
1

Here's my current implementation:

$.liveClickHold = function(selector, fn) {

    $(selector).live("mousedown", function(evt) {

        var $this = $(this).data("mousedown", true);

        setTimeout(function() {
            if ($this.data("mousedown") === true) {
                fn(evt);
            }
        }, 500);

    });

    $(selector).live("mouseup", function(evt) {
        $(this).data("mousedown", false);
    });

}
SnickersAreMyFave
  • 5,047
  • 8
  • 26
  • 24
0

I wrote some code to make it easy

//Add custom event listener
$(':root').on('mousedown', '*', function() {
    var el = $(this),
        events = $._data(this, 'events');
    if (events && events.clickHold) {
        el.data(
            'clickHoldTimer',
            setTimeout(
                function() {
                    el.trigger('clickHold')
                },
                el.data('clickHoldTimeout')
            )
        );
    }
}).on('mouseup mouseleave mousemove', '*', function() {
    clearTimeout($(this).data('clickHoldTimer'));
});

//Attach it to the element
$('#HoldListener').data('clickHoldTimeout', 2000); //Time to hold
$('#HoldListener').on('clickHold', function() {
    console.log('Worked!');
});
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<img src="http://lorempixel.com/400/200/" id="HoldListener">

See on JSFiddle

Now you need just to set the time of holding and add clickHold event on your element

Sergey Semushin
  • 124
  • 1
  • 10