简体   繁体   中英

How to link DOM Element to setTimeout

I'm having a bit of fun with a dynamic background for my website. Now I'm trying to lock the rotating tiles with a mouse-click, but since I revert the tiles to their original position with setTimeout I want to cancel that as well for each individual tile.

// Rotate tiles.
$(".tile").on('mouseover', function () {
    var tile = $(this);
    tile.toggleClass('rotate');

    setTimeout(function () {
        tile.removeClass('rotate');
    }, 4000);
});

// Lock the tiles.
$(".tile").on('click', function () {
    $(this).off('mouseover');
    $(this).toggleClass('rotate');
    // clear timeout?
});

Fiddle

The only viable option I've come up with so far is to assign the tiles a new class with identical css properties to overrule the result of the time-out, which is obviously unlikable. How can this be done?

You can pass the timeout in data:

tile.data("timer",setTimeout(function() {
    tile.removeClass('rotate');
});

Then you can clear the timeout later:

clearTimeout(tile.data("timer"));

Disclaimer: I'm not a jQuery user. Personally I'd attach the property to the DOM element itself, but I'm fairly sure .data() is how you pass data around in jQuery.

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