Reputation: 23302
I am trying to trigger an action as soon as an element on the page is loaded. I am using Jquery's on('load')
functionality to do this.
However it is not working. Here is the code and JSFiddle
console.log("Hi");
$('#complexDiv').on('load', function(){
console.log('Header loaded');
});
HTML
</header>
<body>
<h1>Hello!</h1>
<div id="complexDiv">
<h2>Some text</h2>
<p>A paragraph</p>
<img src="" alt="">
</div>
</body>
Upvotes: 2
Views: 667
Reputation: 1
You can define an animation
property at css
for #complexDiv
element with animation-duration
set to 0s
, use animationstart
event attached to $(window)
, .one()
.
Note, onanimationstart
event attribute can be used at chrome, chromium without jQuery .one()
; firefox 47 did not recognize onanimationstart
event attirbute. Also, @keyframes
should be set for animation-name
at css
, though not properties are required to be set.
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js">
</script>
<style>
#complexDiv {
animation: e 0s;
-moz-animation: e 0s;
-webkit-animation: e 0s;
}
@keyframes e {}
@-moz-keyframes e {}
@-webkit-keyframes e {}
</style>
<script>
$(window).one("animationstart", function(e) {
alert(e.target.id + " " + e.type)
console.log(e.target, e.type);
})
</script>
</head>
<body>
<h1>Hello!</h1>
<div id="complexDiv">
<h2>Some text</h2>
<p>A paragraph</p>
<img alt="" src="" />
</div>
</body>
</html>
plnkr http://plnkr.co/edit/70FF4AyY9URLnwgIZl68?p=preview
Upvotes: 1
Reputation: 2040
I believe load event is only called on elements that require external resources.
From jQuery:
The load event is sent to an element when it and all sub-elements have been completely loaded. This event can be sent to any element associated with a URL: images, scripts, frames, iframes, and the window object.
Case for .ready():
While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed and you can use .ready() for that.
For your situation you can listen to window load or better yet use ready because load is deprecated.
$(window).on('load', function(){
console.log('Header loaded');
});
Upvotes: 4