简体   繁体   中英

Limit JS event to once per day per user

I am hoping to limit the event below to once a day per user. This will be a shadowbox that appears when the user tries to leave the page. I don't want to annoy the user with this every time their mouse leaves the body, so it should only happen the first time they are on the site each day.

$('body').one('mouseleave', function() {
    $('.shadowbox').fadeIn(400)
});

I have been advised that using a cookie would be a good way to do this, but I am inexperienced in using cookies. Thank you!

You can set the cookie in that function with an expiry.

Good documentation is available on this here .

Basically, do a check and set in that function.

$('body').one('mouseleave', function() {
    var cookie = document.cookie; //You need to find the cookie you need here (if it exists, don't do anything)
    return; //if exists
    $('.shadowbox').fadeIn(400)
    document.cookie = "myCookieName=true; expires=(datetime + 1day)"
});

That way, you only get to fade and setting if there isn't a cookie available.

You can find infos about using cookies with javascript here : How do I create and read a value from cookie?

Then, assuming you're using the solution above :

$('body').on('mouseleave', function() {
    var cookie = getCookie('visited');
    if ('' == cookie) {
        $('.shadowbox').fadeIn(400);
        createCookie('visited', 'yes', 1);
    }
});

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