JQuery: hover function, how to add delay

I have jQuery that opens the jQuery dialog box ( http://docs.jquery.com/UI/Dialog ) when you hover over an image like this:

    $(document).ready(function() {
        $("img").hover(function() {

             $("#dialog").dialog();
        });
    });

I have 2 questions 1. When I close the dialog and then attach the image again, the dialog does not appear again, how can I fix it 1. How can I open the window only if the user has hovered the image for a couple of seconds.

+3
source share
3 answers

1 - you need to initialize the dialog first. Code here

$(document).ready( function() { 
  $("#dialog").dialog({ autoOpen: false }); // init without showing

  $("img").bind("mouseover", function() { 
    $("#dialog").dialog('open'); // open the dialog
  }); 

});

2 - just use a counter

var _counter = 0;
var _seconds = 0;

$("img").hover(function() {
    // mouseover
     _counter = setInterval(openDialogNow(), 1000);
}, function() {
    // mouseout
    clearInterval(_counter);
});

function openDialogNow() {
    // this function will run every second while the user does not mouseout the image
    _seconds++; // add 1 to the global variable

    if(_seconds == 3) { // will open in 3 seconds, 3 * 1000 miliseconds
         _seconds = 0;  // reset, so we can reuse later
         $("#dialog").dialog('open'); // open the dialog
    }
}
+4
source

1) mouseover/mouseout mouseenter/mouseleave.

2) : http://cherne.net/brian/resources/jquery.hoverIntent.html. , . , 1 .

+6

use jQuery.delay () method.

http://api.jquery.com/delay/

+1
source

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


All Articles