jQuery on load event Examples
If you are unaware of what the .load() event does, then this article is for your rescue. Read on to find out more about jQuery on load event . Different examples are provided that will help in better understanding.
How to use on load event in jQuery
- First of all, the load here is a JavaScript event.
- This load event is sent to an element when it has completely loaded, along with all it’s sub-elements.
- This load event can be sent to any element associated with a URL such as the window object, any scripts (like JavaScript, jQuery, etc.), images, frames and iframes.
Examples for jquery on load:
So lets say that you want to fire off an action and display a greeting message when the page completely l0ads, including any css, images, javascript files, etc. In such a case you may want to use the following code:
Example 1: Show a greeting alert when the page has completely loaded
$(window).load(function () {
alert('Hi there, stranger!');
});From the above code, we can see that it is really very simple to use the on load event in jQuery. The JavaSript equivalent of the above code would be:
window.onload = function() {
// trigger some action here
}Example 2: Show a greeting alert when an image with ID “#my_image” has completely loaded
$('#my_image').load(function() {
alert('Image has completely loaded!');
});Example 3: Show iframe ID & width when it is completely loaded. Full source code follows:
<html>
<head>
<title>jQuery on load() event examples</title>
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
</head>
<body>
<iframe id="my_iframe" src="https://www.w3schools.com/css/default.asp" scrolling="no" width="500" height="500"></iframe>
<script type="text/javascript">
$('iframe').load(function() {
alert( 'Iframe ID: ' + $(this).attr("id") + '; ' + 'Iframe Width: ' +$(this).attr("width") );
});
</script>
</body>
</html>When you execute the above code, the Iframe ID & width are alerted.
Caveat while using Iframe:
It’s mandatory for the iframe to load some valid content in order to fire off the onload event. Or else, the on load event won’t fire off.
For example, if you replace the HTML code in the above example with the following HTML code, then the jQuery on load event won’t fire off for the Iframe.
<iframe id="my_iframe" scrolling="no" width="500" height="500"></iframe>
Caveat while using jQuery on load event, in general:
For any element that you attach the on load event to, using jQuery, it’s mandatory for the element to be completely loaded in order for the event to fire off. So if you have attached the on load event for an image, but the image has not completed loaded or loaded partially, then the on load event won’t be triggered.
Hope this article helped you in understanding more about the jQuery on load event.
Your Turn!
Do you know of any other uses for on load event in jQuery? Feel free to share by commenting below.