
Automatically fire javascript event after page finishes loading
If you are a developer, you might require to fire a javascript event automatically after the page is loaded.
In simpler words, you may need to activate any function automatically, for example – You may require a pop-up window or a modal to show up automatically on a page. In order to achieve that you can alter your script as follows :
Simple way
<script> $(document).ready(function() { your_function(); }); </script>
Another way
<script> window.onload = function() { // your code here }; </script>
Using jQuery
If you are using jQuery then it is advised to use this code :
<script> jQuery(document).ready(function($) { your_popup(); }); </script>
Deprecated Way
Older method :
<body onLoad="your_function();"> { Body of your Document / Web Page } </body>
What does this code do :
Automatically opens a popup window. Very useful for displaying important messages!
Advancements :
If you want to set a time limit for pop up to appear, you can use setTimeout() or setInterval() function which take a function’s scope as first parameter and time as second parameter (in milliseconds). To stop the timeouts, we can use clearTimeout() or clearInterval() functios. (Please note that all these functions can be used with or without the window prefix)
example usage :
window.setInterval("javascript function", milliseconds); setTimeout(function(){alert("Welcome to JustTechThings.com")}, 5000); // 5 seconds delay
If you have any doubts, leave a comment.