Html alert on load

How to use the alert() method in JavaScript

Many candidates are rejected or down-leveled in technical interviews due to poor performance in behavioral or cultural fit interviews. Ace your interviews with this free course, where you will practice confidently tackling behavioral interview questions.

Alerts in Javascript are dialogue boxes that appear to the user when something important is to be conveyed, just like in real life.

For example, when an alert window pops up, the user has to close it manually in order to proceed with their work.

Is an alert always serious?

  • The most common alert we see is everytime we close a document and we are asked “Do you want to save this document?” This is an example of alert. As the alert box must be closed manually it can prove to be quite useful at times like these.
  • Sometimes when you require certain fields in a google form you can add alerts if the user tries to submit the form, leaving that field empty.
  • Alerts can also be used to give users warnings, like when you open a website and a message pops up that says “This website uses cookies!”.

Hence, alerts are a useful tool to learn!

Understanding alerts through code

1. Alerts using buttons

You can create a button that will display an alert message when clicked. The example below shows you how to do this.

2. Alerts before the page is loaded

An alert message can simply be shown when the HTML file runs, before the user accesses any other elements on the page. The example below shows how to do this.

In the above snippet, the alert method is called in the head section of the HTML file as this allows the message to be shown before the rest of the page is visible. Note that without a button, the alert code is written within the tags.

Читайте также:  Empty function in python

3. Alerts using variables

Alerts dont just show text values. They can also be used to show variable values created within the file. The code example below shows how this is done.

Note that in the snippet below, when passing a variable to the alert method, you are not required to put the variable name in “double quotes”. This signifies that the value given to the alert method is a variable.

As you can see in the below code, from line 4 to 8, we can even put alert messages in methods and call them when needed. This way the same message can be shown in multiple places without having to re-write the code.

Источник

HTML onload Attribute

The onload attribute fires when an object has been loaded.

onload is most often used within the element to execute a script once a web page has completely loaded all content (including images, script files, CSS files, etc.). However, it can be used on other elements as well (see «Supported HTML tags» below).

For input elements, the onload attribute is only supported when

The onload attribute can be used to check the visitor’s browser type and browser version, and load the proper version of the web page based on the information.

Applies to

The onload attribute is part of the Event Attributes, and can be used on the following elements:

Examples

Body Example

Execute a JavaScript immediately after a page has been loaded:

Img Example

Using onload on an element. Alert «Image is loaded» immediately after an image has been loaded:

Input Example

Using onload on an element. Alert «Image is loaded» immediately after an image has been loaded:

Browser Support

The onload attribute has the following browser support for each element:

Element
body Yes Yes Yes Yes Yes
iframe Yes Yes Yes Yes Yes
img Yes Yes Yes Yes Yes
input type=»image» Yes Yes Yes Yes Yes
link Yes Yes Yes Yes Yes
script Yes Yes Yes Yes Yes
style Yes Yes Yes Yes Yes

Источник

JavaScript Alert [Examples And Usage]

Note that, when executed, the alert function will get the focus and prevent the user from interacting with the reset of the website until the modal gets dismisssed.

Examples using alert

1. Alert message on click

A very common use case for the alert fuction is to use it when filling a form and then trying to submit it by clicking a button.

Let’s say we want to make sure the user is over 18 years old when filling the following form:

form name="myForm" action=""> 
label for="age">Agelabel>
input type="number" name="age" id="age" />
button type="submit">Submitbutton>
form>

All we have to do is attach an event listener to the button, checking for the value of the input field and then displaying the modal with the alert function of JavaScript:

var checkAge = (e) =>  
if(document.querySelector('#age').value 18)

// Preventing the submit of the form
e.preventDefault();

// Displaying the modal window
alert("You have to be older 18!");
>
>;

// Listening to the click event on the button
document.querySelector('button').addEventListener('click', checkAge);

2. Alert box before closing the window

It’s also a common practise in websites that require saving changes to display an alert message when the user tries to close the browser’s window or tab.

To do this, we have to first detect when the user is about to close the window. We can achieve this in two different ways, but it’s usually recommended to use event listeners when possible.

// Using event listeners
window.addEventListener("beforeunload", showDialog);

// Overwriting the window default property function
window.onbeforeunload = showDialog;

Now all we have to do is show them a dialog. But in this case, we won’t be using the alert function for this scenario.

Unfortunately we can not customise the message that gets displayed on the dialog anymore. We still have to return a text for old browsers compatibility, but the message will most likely not get displayed on modern browsers. They’ll show a default message telling the user that changes won’t get saved.

So, here’s how we tell the browser we want to show a message, but returning a string on the event function:

var showDialog = (e) =>  
return 'Dialog text here.';
>;
window.addEventListener("beforeunload", showDialog);

3. Alert box on page load

In some very specific cases, websites might want to show an alert message on page load. To do this all we need to do is fire the alert message on the section of our HTML. This way, the alert will be shown before loading any elements on the page.

head> 
script>
alert("Displayed before page loads");
/script>
/head>
body>
Your page content.
/body>

4. Alert message using a variable

Using a variable to display different messages based on its content can also be done quite easily. Simply pass the variable to the alert method instead of a string text.

var myVariable = 'I love alert boxes!!';
alert(myVariable);

5. Alert a message requiring confirmation

Perhaps you want to show an alert that requires the visitors confirmation and that allows them too also cancel or ignore it by displaying a «Cancel» and an «OK» buttons. For these cases we will use the confirm function, which can be seen as a variant of the alert function.

The confirm function will just add a «Cancel» button on top of the «OK» one added by the alert method.

confirm('Do you want to continue?');

We can catch the visitor’s decision by checking the result of the method. It will be true if the visitor clicks on «OK» and false otherwise.

if(confirm("Do you want to continue?")) 
// continue heree
>

6. Alert a message showing input field

In some occassions we might want to capture the user input directly on the alert message. In this cases we will also move away from the alert function and use the alternative function prompt . This function creates the same dialog box but adds a text field to it and the «Cancel» button too.

It admits twoo parameters. The first one is the text to show on the dialog (for the input) and the second one is the default value for the input (if any).

// Showing a dialog box with a text input containing "Steve"
prompt("Enter your name, please:", "Steve");

// Showing a dialog box with ab empty text input.
prompt("Enter your name, please:");

7. Alerts with custom styles

In order to use your own custom alert modals we’ll have to make use of JavaScript and CSS. The easiest, fastest and probably most reliable way to do it is by using external plugins instead of doing it by yourself.

One of the most used ones is SweetAlert2 , or even its predecesor SweetAlert.

Here’s an example of how a confirm alert dialog looks like when using this component:

var showConfirm = (e) =>  
e.preventDefault();

Swal.fire(
title: 'Error!',
text: 'Do you want to continue',
confirmButtonText: 'Yeap!'
>);
>;

document.querySelector('button').addEventListener('click', showConfirm);

As you can see there aren’t huge changes in our code and the usage is quite straight away.

You can check more alert examples using this component on their website.

There are other dialog boxes plugins out there, so feel free to choose the one that fits your needs.

Источник

Оцените статью