How to add onload event to a div element?

How to add onload event to a div element?

How do you add an onload event to an element? Can I use:

for this?

Solutions/Answers:

Solution 1:

No, you can’t. The easiest way to make it work would be to put the function call directly after the element

Example:

...
<div id="somid">Some content</div>
<script type="text/javascript">
   oQuickReply.swap('somid');
</script>
...

or – even better – just in front of </body>:

...
<script type="text/javascript">
   oQuickReply.swap('somid');
</script>
</body>

…so it doesn’t block the following content from loading.

Solution 2:

The onload event can only be used on the document(body) itself, frames, images, and scripts. In other words, it can be attached to only body and/or each external resource. The div is not an external resource and it’s loaded as part of the body, so the onload event doesn’t apply there.

Solution 3:

You can trigger some js automatically on an IMG element using onerror, and no src.

<img src onerror='alert()'>

Solution 4:

onload event it only supports with few tags like listed below.

<body>, <frame>, <iframe>, <img>, <input type="image">, <link>, <script>, <style>

Here the reference for onload event

Related:  Check if a timeout has been cleared?

Solution 5:

Try this! And never use trigger twice on div!

You can define function to call before the div tag.

$(function(){
    $('div[onload]').trigger('onload');
});

DEMO: jsfiddle

Solution 6:

I just want to add here that if any one want to call a function on load event of div & you don’t want to use jQuery(due to conflict as in my case) then simply call a function after all the html code or any other code you have written including the function code and
simply call a function .

/* All Other Code*/
-----
------
/* ----At the end ---- */
<script type="text/javascript">
   function_name();
</script>

OR

/* All Other Code*/
-----
------
/* ----At the end ---- */
<script type="text/javascript">
 function my_func(){
   function definition;      

  }

 my_func();
</script>