How can I create a “first-load” event in html or javascript?

早过忘川 提交于 2019-12-02 03:07:14

Use on load. It will execute when the page loads, and you will see your alert. Good luck with your knowledge.

    <html>
    <head>
    <script>
    function load()
    {
    alert("Page is loaded");
    }
    </script>
    </head>
    <body onload="load()">
    <h1>Hello World!</h1>
    </body>
    </html> 

Edit: You can get more advance and set cookies to see if it's the user's first time, but I'm not sure you're at that level yet, but anyways:

You could for example set a localStorage property like

if(!localStorage["alertdisplayed"]) {
    alert("Your text")
    localStorage["alertdisplayed"] = true
}

Note that localStorage isn't supported by older Browsers.

An alternative would be setting a Cookie and check against its existence

If you don't know how to set / get cookies with javascript, i would suggest, reading this article: https://developer.mozilla.org/en-US/docs/Web/API/document.cookie?redirectlocale=en-US&redirectslug=DOM%2Fdocument.cookie

Localstorage is probably the way to go. Here is a bit of info on it: http://diveintohtml5.info/storage.html

Basically it allows you to store small amounts of data on the user's machine (up to 5mb in most browsers). So all you need to do is set a flag in there letting you know that the user has already visited, and if that flag isn't present on page load, show the message.

// Run function on load, could also run on dom ready
window.onload = function() {
    // Check if localStorage is available (IE8+) and make sure that the visited flag is not already set.
    if(typeof window.localStorage !== "undefined" && !localStorage.getItem('visited')) {
         // Set visited flag in local storage
         localStorage.setItem('visited', true);
         // Alert the user
         alert("Hello my friend. This is your first visit.");   
    }
}

This should work in all browsers where local storage is available. See caniuse.com for reference. http://caniuse.com/#search=localstorage

You have a couple of options: storing a cookie on the client or utilizing the local storage of html5. Either of these could be checked on page load.

Here is a link for getting started with HTML5 web storage:

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

you can do it for chrome in following way

<html>
<head> 
<title>First visit event</title>    
<script> 
function do_something() {
    if(typeof(localStorage.setVisit)=='undefind' || localStorage.setVisit==''){
        localStorage.setVisit='yes';
        alert("Hello my friend. This is your first visit.");
    }
} 
</script>

</head>

<body onload="do_something()"> </body>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!