- Display a Message on the Window Onload Event
- Display the Sum of Two Numbers on the Window Onload Event
Display a Message on the Window Onload Event
An approach is considered to display a simple message by utilizing the window onload function call. JavaScript provides a window.onload event that is triggered during the loading of the webpage. Moreover, users can change the event to trigger a function based on a particular event. The syntax of the window.onload event is provided below:
Syntax
In this syntax, the function “fun()” is called using the window.onload.
Code
The description of the code is given below:
- A function “fun()” is utilized to generate an alert message “Welcome to JavaScript World”.
- After that, the onload event is employed to call the function “fun()”.
Output
The output shows a message “Welcome to JavaScript World” in the alert box by employing the window.onload function.
Display the Sum of Two Numbers on the Window Onload Event
Another method is considered to add two numbers by calling the function using the window.onload event. The following code refers to adding two numbers on the onload event of the window:
Code
The description of the code is as follows:
- The “window.onload” event occurs to call the function in JavaScript.
- A “simpFunction” method is used by passing two arguments “number1” and “number2”.
- In this function, an alert message is generated which will add two numbers, “5” and “10”.
Output
The output shows that an alert box is loaded which shows the sum of “5” and “10”.
That’s it! You have learned to apply window.onload events in JavaScript.
Conclusion
JavaScript provides a window.onload event to call a function on the load event of the window. The function may point towards an alert message, a warning message, or to address any programming query. We have provided two different approaches to using the window.onload event in JavaScript. The first approach prints an alert message on the load event of the window, whereas the second example makes use of the window.onload event to address a mathematical problem.