Pejs
Pejs

Reputation: 265

How to call custom function on hover with delay in jquery

I suppose it's something simple but just can't get my syntax to work.

I created a function that displays popup box with user info, called 'displayUserinfo' (there's a lot of code to it so I guess no point to paste it in). When user clicks on $('.avatar') class, function is launched:

$('.avatar').on('click', displayUserinfo);

And this part works perfctly. Now I want to add code that will launch the same function when user hovers over the $('.avatar') for 2 seconds, but that's where function is not being launched (console.logs are there to test if it's working and they both do):

var timer;
var delay = 2000;

$('.avatar').hover(function() {
    console.log('test1');
    timer = setTimeout(function() {
        console.log('test2');
        $('.avatar').displayUserinfo;
    }, delay);
}, function() {
    clearTimeout(timer);
    console.log('test3');
});

I tried $(this).displayUserinfo but didn't work either.

Can anyone give me a hand on that please?

Upvotes: 0

Views: 347

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074028

This line:

$('.avatar').displayUserinfo;

...looks for any elements with the avatar class and wraps them in a jQuery object, then accesses a displayUserinfo property on that jQuery object (which is probably undefined) — and then does nothing with it. It doesn't, for instance, call a function (other than $()).

I think you probably wanted:

var hovered = this;

just inside the hover callback, and then this inside the setTimeout callback:

displayUserinfo.call(hovered);

That calls the displayUserinfo function, using the element that was hovered as this during the call (the way on does).

In situ:

var timer;
var delay = 1000;

$('.avatar').hover(function() {
    var hovered = this;
    timer = setTimeout(function() {
        console.log('test2');
        displayUserinfo.call(hovered);
    }, delay);
}, function() {
    clearTimeout(timer);
});

Side note: The delay in your code is only one second, not two.

Upvotes: 2

Related Questions