Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript prompt loads before page displays

I added a prompt on my page but it loads before the page has loaded.
How do I only show the message once the whole page is visible?

Here is my prompt:

if (name == null || name == "") {
  txt == "No name provided";
} else {
  txt = "Hello, " + name + "! How are you today?";
}
alert(txt);


    

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If you wrap the code in an event-listener that listens for the DOMContentLoaded event it’ll run only once the document is ready:

window.addEventListener('DOMContentLoaded', (e)=>{
  if (name == null || name == "") {
    txt == "No name provided";
  } else {
    txt = "Hello, " + name + "! How are you today?";
  }
  alert(txt);
});

I have, however, adjusted your original code to:

window.addEventListener('DOMContentLoaded', (e) => {
  // assign the name via the prompt() interface, and
  // declare both variables (rather than accidentally
  // creating globals):
  let name = prompt("Hi, what's your name?"),
      txt;
  // name won't be null, but it may be falsey, so here
  // we check if the name is falsey:
  if (!name) {
    // if the user cancels the prompt, prompt() returns
    // false; if they provide an empty-string that
    // empty string is falsey:
    txt = "No name provided";
  // if the name variable is truthy:
  } else {
    // we use a template literal String to interpolate
    // the variable 'name' into that string:
    txt = `Hello, ${name}! How are you today?`;
  }
  // I wouldn't recommend alert, but I left this unchanged:
  alert(txt);
});

JS Fiddle demo.

References:

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading