Search code examples
javascripthtmleventsdom-eventsvisited

How can I create a "first-load" event in html or Javascript?


I'm starter. I have an idea. I want to implement an event like this. Is it possible?

<html>
<head>
<title>First visit event</title>

<script>
function do_something()
{
    alert("Hello my friend. This is your first visit.");
}
</script>

</head>

<body firstVisitEvent="do_something()">
</body>

Solution

  • 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