To trigger the window.focus event on page load, you can simply call the focus method on the window object inside the DOMContentLoaded event handler. This will ensure that the focus event is triggered when the page has finished loading. Here's how you can do it:

<!DOCTYPE html> <html> <head> <title>Page Load Focus Event</title> </head> <body> <!-- Your page content --> <script> document.addEventListener('DOMContentLoaded', function() { window.focus(); // Trigger the focus event on page load }); </script> </body> </html>

When the page loads, the DOMContentLoaded event fires once all the DOM content has been loaded, and the window.focus method is called, triggering the focus event on the window object.

Please note that the window.focus method might not have any visible effect on the page because it depends on the browser's behavior and the context in which the page is being loaded. In some cases, it may not work as expected, especially if the browser or user settings prevent focus changes on page load.

If you have specific requirements for focusing on a particular element within the page, you can use the focus method on the DOM element itself instead of triggering the window.focus event. For example, if you want to focus on an input element with the ID "myInput" on page load, you can do the following:

<!DOCTYPE html> <html> <head> <title>Page Load Focus Element</title> </head> <body> <!-- Your page content --> <input type="text" id="myInput"> <script> document.addEventListener('DOMContentLoaded', function() { document.getElementById('myInput').focus(); // Focus on the input element with ID "myInput" }); </script> </body> </html>

Using the focus method on a specific DOM element will be more reliable and effective than triggering the window.focus event, especially when trying to set focus to a particular form element or interactive element on page load.

Have questions or queries?
Get in Touch