javascriptjquerylong-click

How to use jQuery longclick?


I am using datatables plugin and using this for click:

$('.datatable').on('click', 'img#openpli-playlist', function(e) {
    alert("You clicked OPENPLI ICON!");
});

Now I need to use jQuery plugin longclick and using this:

$('.datatable').longClick(function(e) {
    alert("You clicked OPENPLI ICON!");
},1000);

So the problem is how can I add selector to longclick I try this for selector but is not working:

$('.datatable img#openpli-playlist').longClick(function(e) {
    alert("You clicked OPENPLI ICON!");
},1000);

Can someone give me solution why is this not working?

Thanks


Solution

  • Simple fix will be:

    var tmr = 0;
    $(element).mousedown(function () {
      tmr = setTimeout(function () {
        alert("You clicked for 1 second! Wow!");
      }, 1000);
    }).mouseup(function () {
      clearTimeout(tmr);
    });
    

    Now this can be used in delegation too:

    var tmr = 0;
    $(static_parent).on("mousedown", element, function () {
      tmr = setTimeout(function () {
        alert("You clicked for 1 second! Wow!");
      }, 1000);
    }).on("mouseup", element, function () {
      clearTimeout(tmr);
    });
    

    Your solution:

    var tmr = 0;
    $('.datatable').on('mousedown', 'img#openpli-playlist', function(e) {
      tmr = setTimeout(function () {
        alert("You clicked OPENPLI ICON!");
      }, 1000);
    }).on('mouseup', 'img#openpli-playlist', function(e) {
      clearTimeout(tmr);
    });
    

    As an improvement to previous answers, you can distinguish between click and long press in this way:

    var tmr = 0;
    var islong = 0;
    
    $(element)
      .mousedown(function () {
        tmr = setTimeout(function () {
          // Handle the long-press
          alert("You clicked for 1 second!");
          console.log("You clicked for 1 second!");
          islong = 1;
        }, 1000);
      })
      .mouseup(function () {
        if (islong == 0) {
          // Handle the click
          alert("This is a click!");
          console.log("This is a click!");
        }
        islong = 0;
        clearTimeout(tmr);
      });