JavaScript Window Events 🎯

beginner
25 min

JavaScript Window Events 🎯

Welcome to our comprehensive guide on JavaScript Window Events! In this lesson, we'll delve into the world of window events, which are essential for creating interactive and dynamic web pages. Let's get started! 📝

What are Window Events?

Window events are actions that occur when something happens in the browser window. For example, when a user clicks a button, loads a webpage, or scrolls down, these are all window events. JavaScript allows us to react to these events and perform specific actions. 💡

Core Window Events 📝

Here are some fundamental window events that every JavaScript developer should know:

  1. load: This event is triggered when the entire webpage, including all its resources, has been loaded.
javascript
window.addEventListener('load', function() { console.log('Page has finished loading.'); });
  1. resize: This event is fired when the browser window is resized.
javascript
window.addEventListener('resize', function() { console.log('Window has been resized.'); });
  1. scroll: This event is triggered when the user scrolls the window.
javascript
window.addEventListener('scroll', function() { console.log('User has scrolled.'); });

Advanced Window Events 📝

  1. beforeunload: This event is fired just before the current page is unloaded, either by the user closing the browser, navigating to a different page, or refreshing the page.
javascript
window.addEventListener('beforeunload', function(event) { event.returnValue = 'Are you sure you want to leave?'; });

Event Handling 📝

To handle window events, we use event listeners. We attach an event listener to the window object, and it listens for specific events. When the event occurs, the function passed to the event listener is executed. 💡

Quiz 📝

Quick Quiz
Question 1 of 1

What event is fired when a user scrolls the window?

Practice 🎯

  1. Create a webpage that alerts the user when the page has finished loading.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>JavaScript Window Events</title> </head> <body> <script> window.addEventListener('load', function() { alert('Page has finished loading.'); }); </script> </body> </html>
  1. Modify the above webpage to display a message when the window is resized.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>JavaScript Window Events</title> </head> <body> <script> window.addEventListener('load', function() { window.addEventListener('resize', function() { alert('Window has been resized.'); }); }); </script> </body> </html>

We hope you enjoyed this lesson on JavaScript Window Events! Stay tuned for more engaging and informative tutorials at CodeYourCraft. Happy coding! 💡