简体   繁体   中英

How do I add a delay to the mouseover function?

I'm making a calendar app using the jQuery plugin FullCalendar and I made a tab to the left of the calendar with the weeks from 1-6 on it. When the user drags their mouse over one of the weeks the calendar switches to the view of the respective view. This works but it can be annoying for the user if they do it accidentally. So, I want to add a delay to the function so that it will only happen if the user has their mouse on it for a few hundred milliseconds so it will happen less without the user wanting it to happen.

$('#week3').mouseover(function() {
    $('#week3').css('color', 'white');
    $('#week3').css('background-color', '#6B8BA9');
    $('#week3').week3();

I want to add a short delay before $('#week3').css('color', 'white');

Use a timeout :

$('#week3').on({
    mouseenter: function() {
        var that = this;

        $(that).data('timer', 
            setTimeout(function() {
                $(that).css('color', 'white');
            },1000)
        ).css('background-color', '#6B8BA9').week3();
    },
    mouseleave: function() {
        clearTimeout( $(this).data('timer') );
    }
});

If I am understanding you correctly, then you will need a more complete solution like below

var mouse_monitor

$('#week3').mouseover(function() {
  mouse_monitor = setTimeout(function(){
    $('#week3').css('color', 'white');
    $('#week3').css('background-color', '#6B8BA9');
    $('#week3').week3();
  }, 1500)
}); 

$('#week3').mouseout(function() { clearTimeout( mouse_monitor ); }

The var mouse_monitor is a global reference to your timeout function. The mouseout function is missing in other post, which assures that your mouseover function will not fire if the user moves the mouse off the hover target before the value of the setTimeout expires. Other examples will still invoke your mouseover function everytime, but with just an added delay, so they won't work for what I think you are trying to achieve.

您正在寻找setTimeout

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM