Oscar Rojas
Oscar Rojas

Reputation: 1

How to show a javascript alert just one time

See, this is my code for the alert:

function Alerta() {
	 var person = prompt("¡Recuerda!:Todos Los Titulos Abren El Menu!\nCual es tu nombre?", "Goku");
    
    if (person != null) {
        document.getElementById("intro").innerHTML =
        "" + person + "";
		}
}
<html>
<head>
</head>
<body onLoad="Alerta()" id="Inicio">
</body>

The problem is that it shows up every time I enter in the page, refresh the page...or blink, so... I want it to do this: when you write a name and click "accept" it saves the name and the alert is never shown again, and when you click "cancel" it will show it every time you enter the page. Help please?

Upvotes: 0

Views: 1188

Answers (2)

synthet1c
synthet1c

Reputation: 6282

You could use localStorage to save the persons name between sessions, then only prompt if the person value is not set in localStorage. If you need backwards compatibility you can use cookies in place of localStorage

function Alerta() {
  // get the value from localStorage
  var person = localStorage.person
  if (!person) {
    // person has not been set so ask the user
    person = prompt("¡Recuerda!:Todos Los Titulos Abren El Menu!\nCual es tu nombre?", "Goku");
    // set the person value in localStorage for next time
    localStorage.person = person
  }
  // set the value of your intro
  document.getElementById("intro").innerHTML = person;
}

Upvotes: 2

When they enter a name, save it to something that persists across pages (like a cookie or local storage), and if it's already set, suppress the prompt when the page loads.

Upvotes: 0

Related Questions