Thamidu de Harshitha
Thamidu de Harshitha

Reputation: 383

How to prevent an alert run after the first run

I'm not good in HTML & JavaScript.

How can I prevent javascript running after the first run. Lets imagine I loaded the first page and I went to another page from a link of it. IN THE FIRST PAGE THERE IS AN ALERT RUNNING BY JS. so when i came back to the first page the alert will be shown HOW CAN I PREVENT THIS?

this is my code.(it just a little once)

<script type="text/javascript">
    function name(me)
    {
      document.write(me);
    }

    me=window.prompt("Enter your Name before Proceed");
    name(me);
</script>

Upvotes: 0

Views: 185

Answers (2)

shshaw
shshaw

Reputation: 3213

The simplest way to prompt on first visit, and not prompt on revisit would be to set the name using a cookie.

   var me = document.cookie.replace(/(?:(?:^|.*;\s*)me\s*\=\s*([^;]*).*$)|^.*$/, "$1");
   if ( !me ) {
     me = window.prompt('Enter your Name before Proceed');
     document.cookie = 'me='+me+'; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/';
   }
   name(me);

The first line checks if the name has already been stored in the cookie, and if nothing is returned then the prompt asks the user for their name which is then added to the cookie for future visits.

Upvotes: 1

Anders Lind&#233;n
Anders Lind&#233;n

Reputation: 7323

You can use localStorage:

<script type="text/javascript">
    var me = localStorage.getItem("name");
    if (me == null)
    {
      me = window.prompt("Enter your Name before Proceed");
      localStorage.setItem("name", me);
    }
    document.write(me);
</script>

Update

By using sessionStorage instead of localStorage, the data will be kept only for one session, meaning that if you close the browser window, the data will be forgotten. Maybe that is more appropriate?

Upvotes: 0

Related Questions