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! 📝
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. 💡
Here are some fundamental window events that every JavaScript developer should know:
load: This event is triggered when the entire webpage, including all its resources, has been loaded.window.addEventListener('load', function() {
console.log('Page has finished loading.');
});resize: This event is fired when the browser window is resized.window.addEventListener('resize', function() {
console.log('Window has been resized.');
});scroll: This event is triggered when the user scrolls the window.window.addEventListener('scroll', function() {
console.log('User has scrolled.');
});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.window.addEventListener('beforeunload', function(event) {
event.returnValue = 'Are you sure you want to leave?';
});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. 💡
What event is fired when a user scrolls the window?
<!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><!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! 💡