Mousehold event in jQuery

Basically, I have this image using the left and right arrow buttons. This image, by default, is the first frame that I extracted from some gif, the original gif contains 31 frames. My goal is when users press the right arrow button, I want to display the next frame and so on ... Everything works fine, as shown below. However, I need to add some kind of mouse event so that when the user clicks and holds the mouse, I want to continue to shoot at the following images. How can I achieve this?

$('#arrow_right').click(function (event) { event.preventDefault(); var data_id = parseInt($(this).parent().find('#inner_wrap img').attr('data-id')); if (data_id >= 1 && data_id <= 30) { data_id = data_id + 1; var avatar_num = $('#inner_wrap').html('<img id="avatar" data-id="' + data_id + '" src="img/avatar_test' + data_id + '.gif" width="90" height="200">'); } }); 
+4
source share
2 answers

Well, you can use the mousedown event to trigger a function that displays a gif frame: http://api.jquery.com/mousedown/ , and then add another event handler for the mouseup event, which will stop this function. This function can be called via setInterval() in mousedown -event, for example, and will stop through clearInterval() in the mouseup event.

This is an example showing the principle:

 var interval; $(button).addEventListener('mousedown',function(e) { interval = setInterval(function() { // here goes your code that displays your image/replaces the one that is already there },500); // 500ms between each frame }); $(button).addEventListener('mouseup',function(e) { clearInterval(interval); }); // Thank you, Timo002, for your contribution! // This code will stop the interval if you move your mouse away from the button while still holding it. $(button).addEventListener('mouseout',function(e) { clearInterval(interval); }); 
+15
source

In addition to Zim84's answer, I have to add this piece of code!

 $(button).addEventListener('mouseout',function(e) { clearInterval(interval); }); 

This will make sure that someone clicks the ( mousedown ) button and holds the mouse button and leaves the mouseout button, the interval is also cleared. Without this, the interval does not stop in this particular situation.

+4
source

Source: https://habr.com/ru/post/1482319/


All Articles