Run jQuery code only the first time a user visits

2020-03-30 01:28发布

I have this code

setTimeout(function () {
    $("#videoOverlay").fadeIn();
    document.getElementById("video").play();
}, 8000);

This means 8 seconds after loading, a pop-up will come up and a video will play. I only want this to come up the first time I visit the site. How can I do this with jQuery?

2条回答
Bombasti
2楼-- · 2020-03-30 01:48

you could try this jquery cookie plugin https://github.com/js-cookie/js-cookie

and then you can use it with

Cookies.get('name'); 
Cookies.set('name','value'); 
查看更多
▲ chillily
3楼-- · 2020-03-30 02:05

Try with localStorage instead of cookie:

if (!localStorage.getItem('viewed')){
    setTimeout(function () {
        $("#videoOverlay").fadeIn();
        document.getElementById("video").play();
        localStorage.setItem('viewed','yes');
    }, 8000);
};

To delete it:

localStorage.removeItem('viewed');

With local storage, web applications can store data locally within the user's browser.

FROM http://www.w3schools.com/html/html5_webstorage.asp

What is HTML Local Storage?

Before HTML5, application data had to be stored in cookies, included in every server request. Local storage is more secure, and large amounts of data can be stored locally, without affecting website performance.

Unlike cookies, the storage limit is far larger (at least 5MB) and information is never transferred to the server.

Local storage is per origin (per domain and protocol). All pages, from one origin, can store and access the same data.

Using: sessionStorage

You can also use sessionStorage object that is equal to the localStorage object, except that it stores the data for only one session. The data is deleted when the user closes the specific browser tab.

if (!sessionStorage.viewed){
    setTimeout(function () {
        $("#videoOverlay").fadeIn();
        document.getElementById("video").play();
        sessionStorage.viewed=1
    }, 8000);
};
查看更多
登录 后发表回答