[javascript] How to add onload event to a div element

How do you add an onload event to an element?

Can I use:

<div onload="oQuickReply.swap();" ></div>

for this?

This question is related to javascript html

The answer is


we can use all these tags with onload

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

eg:

_x000D_
_x000D_
function loadImage() {
    alert("Image is loaded");
}
_x000D_
<img src="https://www.w3schools.com/tags/w3html.gif" onload="loadImage()" width="100" height="132">
_x000D_
_x000D_
_x000D_


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


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


You can attach an event listener as below. It will trigger whenever the div having selector #my-id loads completely to DOM.

$(document).on('EventName', '#my-id', function() {
 // do something
});

Inthis case EventName may be 'load' or 'click'

https://api.jquery.com/on/#on-events-selector-data-handler


use an iframe and hide it iframe works like a body tag

<!DOCTYPE html>
<html>
<body>

<iframe style="display:none" onload="myFunction()" src="http://www.w3schools.com"></iframe>
<p id="demo"></p>

<script>
function myFunction() {
    document.getElementById("demo").innerHTML = "Iframe is loaded.";
}
</script>

</body>
</html>

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.


First to answer your question: No, you can't, not directly like you wanted to do so. May be a bit late to answer, but this is my solution, without jQuery, pure javascript. It was originally written to apply a resize function to textareas after DOM is loaded and on keyup.

Same way you could use it to do something with (all) divs or only one, if specified, like so:

document.addEventListener("DOMContentLoaded", function() {
    var divs = document.querySelectorAll('div'); // all divs
    var mydiv = document.getElementById('myDiv'); // only div#myDiv
    divs.forEach( div => {
        do_something_with_all_divs(div);
    });
    do_something_with_mydiv(mydiv);
});

If you really need to do something with a div, loaded after the DOM is loaded, e.g. after an ajax call, you could use a very helpful hack, which is easy to understand an you'll find it ...working-with-elements-before-the-dom-is-ready.... It says "before the DOM is ready" but it works brillant the same way, after an ajax insertion or js-appendChild-whatever of a div. Here's the code, with some tiny changes to my needs.

css

.loaded { // I use only class loaded instead of a nodename
    animation-name: nodeReady;
    animation-duration: 0.001s;
}

@keyframes nodeReady {  
    from { clip: rect(1px, auto, auto, auto); }
    to { clip: rect(0px, auto, auto, auto); }  
}

javascript

document.addEventListener("animationstart", function(event) {
    var e = event || window.event;
    if (e.animationName == "nodeReady") {
        e.target.classList.remove('loaded');
        do_something_else();
    }
}, false);

You could use an interval to check for it until it loads like this: https://codepen.io/pager/pen/MBgGGM

let checkonloadDoSomething = setInterval(() => {
  let onloadDoSomething = document.getElementById("onloadDoSomething");
  if (onloadDoSomething) {
    onloadDoSomething.innerHTML="Loaded"
    clearInterval(checkonloadDoSomething);
  } else {`enter code here`
    console.log("Waiting for onloadDoSomething to load");
  }
}, 100);

Avoid using any interval based methods and use MutationObserver targeting a parent div of dynamically loaded div for better efficiency.

Here's the simple snippet:

HTML:

<div class="parent-static-div">
  <div class="dynamic-loaded-div">
    this div is loaded after DOM ready event
  </div>
</div>

JS:

var observer = new MutationObserver(function (mutationList, obsrvr) {
  var div_to_check = document.querySelector(".dynamic-loaded-div"); //get div by class
  // var div_to_check = document.getElementById('div-id'); //get div by id

  console.log("checking for div...");
  if (div_to_check) {
    console.log("div is loaded now"); // DO YOUR STUFF!
    obsrvr.disconnect(); // stop observing
    return;
  }
});

var parentElement = document.querySelector("parent-static-div"); // use parent div which is already present in DOM to maximise efficiency
// var parentElement = document // if not sure about parent div then just use whole 'document'

// start observing for dynamic div
observer.observe(parentElement, {
  // for properties details: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserverInit
  childList: true,
  subtree: true,
});

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

<img src onerror='alert()'>

Since the onload event is only supported on a few elements, you have to use an alternate method.

You can use a MutationObserver for this:

_x000D_
_x000D_
const trackElement = element => {_x000D_
  let present = false;_x000D_
  const checkIfPresent = () => {_x000D_
    if (document.body.contains(element)) {_x000D_
      if (!present) {_x000D_
        console.log('in DOM:', element);_x000D_
      }_x000D_
      present = true;_x000D_
    } else if (present) {_x000D_
      present = false;_x000D_
      console.log('Not in DOM');_x000D_
    }_x000D_
  };_x000D_
_x000D_
  const observer = new MutationObserver(checkIfPresent);_x000D_
  observer.observe(document.body, { childList: true });_x000D_
  checkIfPresent();_x000D_
_x000D_
  return observer;_x000D_
};_x000D_
_x000D_
const element = document.querySelector('#element');_x000D_
const add = () => document.body.appendChild(element);_x000D_
const remove = () => element.remove();_x000D_
_x000D_
trackElement(element);
_x000D_
<button onclick="add()">Add</button>_x000D_
<button onclick="remove()">Remove</button>_x000D_
_x000D_
<div id="element">Element</div>
_x000D_
_x000D_
_x000D_


As all said, you cannot use onLoad event on a DIV instead but it before body tag.

but in case you have one footer file and include it in many pages. it's better to check first if the div you want is on that page displayed, so the code doesn't executed in the pages that doesn't contain that DIV to make it load faster and save some time for your application.

so you will need to give that DIV an ID and do:

var myElem = document.getElementById('myElementId');
if (myElem !== null){ put your code here}

When you load some html from server and insert it into DOM tree you can use DOMSubtreeModified however it is deprecated - so you can use MutationObserver or just detect new content inside loadElement function directly so you will don't need to wait for DOM events

_x000D_
_x000D_
var ignoreFirst=0;_x000D_
var observer = (new MutationObserver((m, ob)=>_x000D_
{_x000D_
  if(ignoreFirst++>0) {_x000D_
    console.log('Element add on', new Date());_x000D_
  }_x000D_
}_x000D_
)).observe(content, {childList: true, subtree:true });_x000D_
_x000D_
_x000D_
// simulate element loading_x000D_
var tmp=1;_x000D_
function loadElement(name) {  _x000D_
  setTimeout(()=>{_x000D_
    console.log(`Element ${name} loaded`)_x000D_
    content.innerHTML += `<div>My name is ${name}</div>`; _x000D_
  },1500*tmp++)_x000D_
}; _x000D_
_x000D_
loadElement('Michael');_x000D_
loadElement('Madonna');_x000D_
loadElement('Shakira');
_x000D_
<div id="content"><div>
_x000D_
_x000D_
_x000D_


I needed to have some initialization code run after a chunk of html (template instance) was inserted, and of course I didn't have access to the code that manipulates the template and modifies the DOM. The same idea holds for any partial modification of the DOM by insertion of an html element, usually a <div>.

Some time ago, I did a hack with the onload event of a nearly invisible <img> contained in a <div>, but discovered that a scoped, empty style will also do:

<div .... >
<style scoped="scoped" onload="dosomethingto(this.parentElement);" >   </style>
.....
</div>

Update(Jul 15 2017) - The <style> onload is not supported in last version of IE. Edge does support it, but some users see this as a different browser and stick with IE. The <img> element seems to work better across all browsers.

<div...>
<img onLoad="dosomthing(this.parentElement);" src="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" />
...
</div>

To minimize the visual impact and resource usage of the image, use an inline src that keeps it small and transparent.

One comment I feel I need to make about using a <script>is how much harder it is to determine which <div> the script is near, especially in templating where you can't have an identical id in each instance that the template generates. I thought the answer might be document.currentScript, but this is not universally supported. A <script> element cannot determine its own DOM location reliably; a reference to 'this' points to the main window, and is of no help.

I believe it is necessary to settle for using an <img> element, despite being goofy. This might be a hole in the DOM/javascript framework that could use plugging.


You cannot add event onload on div, but you can add onkeydown and trigger onkeydown event on document load

_x000D_
_x000D_
$(function ()_x000D_
{_x000D_
  $(".ccsdvCotentPS").trigger("onkeydown");_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>_x000D_
_x000D_
<div  onkeydown="setCss( );"> </div>`
_x000D_
_x000D_
_x000D_


In November 2019, I am seeking a way to create a (hypothetical) onparse EventListener for <elements> which don't take onload.

The (hypothetical) onparse EventListener must be able to listen for when an element is parsed.


Third Attempt (and Definitive Solution)

I was pretty happy with the Second Attempt below, but it just struck me that I can make the code shorter and simpler, by creating a tailor-made event:

let parseEvent = new Event('parse');

This is the best solution yet.

The example below:

  1. Creates a tailor-made parse Event
  2. Declares a function (which can be run at window.onload or any time) which:
    • Finds any elements in the document which include the attribute data-onparse
    • Attaches the parse EventListener to each of those elements
    • Dispatches the parse Event to each of those elements to execute the Callback

Working Example:

_x000D_
_x000D_
// Create (homemade) parse event_x000D_
let parseEvent = new Event('parse');_x000D_
_x000D_
// Create Initialising Function which can be run at any time_x000D_
const initialiseParseableElements = () => {_x000D_
_x000D_
  // Get all the elements which need to respond to an onparse event_x000D_
  let elementsWithParseEventListener = document.querySelectorAll('[data-onparse]');_x000D_
  _x000D_
  // Attach Event Listeners and Dispatch Events_x000D_
  elementsWithParseEventListener.forEach((elementWithParseEventListener) => {_x000D_
_x000D_
    elementWithParseEventListener.addEventListener('parse', updateParseEventTarget, false);_x000D_
    elementWithParseEventListener.dataset.onparsed = elementWithParseEventListener.dataset.onparse;_x000D_
    elementWithParseEventListener.removeAttribute('data-onparse');_x000D_
    elementWithParseEventListener.dispatchEvent(parseEvent);_x000D_
  });_x000D_
}_x000D_
_x000D_
// Callback function for the Parse Event Listener_x000D_
const updateParseEventTarget = (e) => {_x000D_
  _x000D_
  switch (e.target.dataset.onparsed) {_x000D_
_x000D_
    case ('update-1') : e.target.textContent = 'My First Updated Heading'; break;_x000D_
    case ('update-2') : e.target.textContent = 'My Second Updated Heading'; break;_x000D_
    case ('update-3') : e.target.textContent = 'My Third Updated Heading'; break;_x000D_
    case ('run-oQuickReply.swap()') : e.target.innerHTML = 'This <code>&lt;div&gt;</code> is now loaded and the function <code>oQuickReply.swap()</code> will run...'; break;_x000D_
  }_x000D_
}_x000D_
_x000D_
// Run Initialising Function_x000D_
initialiseParseableElements();_x000D_
_x000D_
let dynamicHeading = document.createElement('h3');_x000D_
dynamicHeading.textContent = 'Heading Text';_x000D_
dynamicHeading.dataset.onparse = 'update-3';_x000D_
_x000D_
setTimeout(() => {_x000D_
_x000D_
  // Add new element to page after time delay_x000D_
  document.body.appendChild(dynamicHeading);_x000D_
_x000D_
  // Re-run Initialising Function_x000D_
  initialiseParseableElements();_x000D_
_x000D_
}, 3000);
_x000D_
div {_x000D_
  width: 300px;_x000D_
  height: 40px;_x000D_
  padding: 12px;_x000D_
  border: 1px solid rgb(191, 191, 191);_x000D_
}_x000D_
_x000D_
h3 {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
right: 0;_x000D_
}
_x000D_
<h2 data-onparse="update-1">My Heading</h2>_x000D_
<h2 data-onparse="update-2">My Heading</h2>_x000D_
<div data-onparse="run-oQuickReply.swap()">_x000D_
This div hasn't yet loaded and nothing will happen._x000D_
</div>
_x000D_
_x000D_
_x000D_


Second Attempt

The First Attempt below (based on @JohnWilliams' brilliant Empty Image Hack) used a hardcoded <img /> and worked.

I thought it ought to be possible to remove the hardcoded <img /> entirely and only dynamically insert it after detecting, in an element which needed to fire an onparse event, an attribute like:

data-onparse="run-oQuickReply.swap()"

It turns out, this works very well indeed.

The example below:

  1. Finds any elements in the document which include the attribute data-onparse
  2. Dynamically generates an <img src /> and appends it to the document, immediately after each of those elements
  3. Fires the onerror EventListener when the rendering engine parses each <img src />
  4. Executes the Callback and removes that dynamically generated <img src /> from the document

Working Example:

_x000D_
_x000D_
// Get all the elements which need to respond to an onparse event_x000D_
let elementsWithParseEventListener = document.querySelectorAll('[data-onparse]');_x000D_
_x000D_
// Dynamically create and position an empty <img> after each of those elements _x000D_
elementsWithParseEventListener.forEach((elementWithParseEventListener) => {_x000D_
_x000D_
  let emptyImage = document.createElement('img');_x000D_
  emptyImage.src = '';_x000D_
  elementWithParseEventListener.parentNode.insertBefore(emptyImage, elementWithParseEventListener.nextElementSibling);_x000D_
});_x000D_
_x000D_
// Get all the empty images_x000D_
let parseEventTriggers = document.querySelectorAll('img[src=""]');_x000D_
_x000D_
// Callback function for the EventListener below_x000D_
const updateParseEventTarget = (e) => {_x000D_
_x000D_
  let parseEventTarget = e.target.previousElementSibling;_x000D_
  _x000D_
  switch (parseEventTarget.dataset.onparse) {_x000D_
_x000D_
    case ('update-1') : parseEventTarget.textContent = 'My First Updated Heading'; break;_x000D_
    case ('update-2') : parseEventTarget.textContent = 'My Second Updated Heading'; break;_x000D_
    case ('run-oQuickReply.swap()') : parseEventTarget.innerHTML = 'This <code>&lt;div&gt;</code> is now loaded and the function <code>oQuickReply.swap()</code> will run...'; break;_x000D_
  }_x000D_
  _x000D_
  // Remove empty image_x000D_
  e.target.remove();_x000D_
}_x000D_
_x000D_
// Add onerror EventListener to all the empty images_x000D_
parseEventTriggers.forEach((parseEventTrigger) => {_x000D_
  _x000D_
  parseEventTrigger.addEventListener('error', updateParseEventTarget, false);_x000D_
  _x000D_
});
_x000D_
div {_x000D_
  width: 300px;_x000D_
  height: 40px;_x000D_
  padding: 12px;_x000D_
  border: 1px solid rgb(191, 191, 191);_x000D_
}
_x000D_
<h2 data-onparse="update-1">My Heading</h2>_x000D_
<h2 data-onparse="update-2">My Heading</h2>_x000D_
<div data-onparse="run-oQuickReply.swap()">_x000D_
This div hasn't yet loaded and nothing will happen._x000D_
</div>
_x000D_
_x000D_
_x000D_


First Attempt

I can build on @JohnWilliams' <img src> hack (on this page, from 2017) - which is, so far, the best approach I have come across.

The example below:

  1. Fires the onerror EventListener when the rendering engine parses <img src />
  2. Executes the Callback and removes the <img src /> from the document

Working Example:

_x000D_
_x000D_
let myHeadingLoadEventTrigger = document.getElementById('my-heading-load-event-trigger');_x000D_
_x000D_
const updateHeading = (e) => {_x000D_
_x000D_
  let myHeading = e.target.previousElementSibling;_x000D_
  _x000D_
  if (true) { // <= CONDITION HERE_x000D_
    _x000D_
    myHeading.textContent = 'My Updated Heading';_x000D_
  }_x000D_
  _x000D_
  // Modern alternative to document.body.removeChild(e.target);_x000D_
  e.target.remove();_x000D_
}_x000D_
_x000D_
myHeadingLoadEventTrigger.addEventListener('error', updateHeading, false);
_x000D_
<h2>My Heading</h2>_x000D_
<img id="my-heading-load-event-trigger" src />
_x000D_
_x000D_
_x000D_


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>

Use the body.onload event instead, either via attribute (<body onload="myFn()"> ...) or by binding an event in Javascript. This is extremely common with jQuery:

$(document).ready(function() {
    doSomething($('#myDiv'));
});

we can use MutationObserver to solve the problem in efficient way adding a sample code below

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style>
        #second{
            position: absolute;
            width: 100px;
            height: 100px;
            background-color: #a1a1a1;
        }
    </style>
</head>
<body>
<div id="first"></div>
<script>
    var callthis = function(element){
           element.setAttribute("tabIndex",0);
        element.focus();
        element.onkeydown = handler;
        function handler(){
                alert("called")
        }
    }


    var observer = new WebKitMutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            for (var i = 0; i < mutation.addedNodes.length; i++)
            if(mutation.addedNodes[i].id === "second"){
                callthis(mutation.addedNodes[i]);
            }

        })
    });
    observer.observe(document.getElementById("first"), { childList: true });


    var ele = document.createElement('div');
    ele.id = "second"

    document.getElementById("first").appendChild(ele);

</script>

</body>
</html>

I had the same question and was trying to get a Div to load a scroll script, using onload or load. The problem I found was that it would always work before the Div could open, not during or after, so it wouldn't really work.

Then I came up with this as a work around.

<body>

<span onmouseover="window.scrollTo(0, document.body.scrollHeight);" 
onmouseout="window.scrollTo(0, document.body.scrollHeight);">

<div id="">
</div>

<a href="" onclick="window.scrollTo(0, document.body.scrollHeight);">Link to open Div</a>

</span>
</body>

I placed the Div inside a Span and gave the Span two events, a mouseover and a mouseout. Then below that Div, I placed a link to open the Div, and gave that link an event for onclick. All events the exact same, to make the page scroll down to bottom of page. Now when the button to open the Div is clicked, the page will jump down part way, and the Div will open above the button, causing the mouseover and mouseout events to help push the scroll down script. Then any movement of the mouse at that point will push the script one last time.


I really like the YUI3 library for this sort of thing.

<div id="mydiv"> ... </div>

<script>
YUI().use('node-base', function(Y) {
  Y.on("available", someFunction, '#mydiv')
})

See: http://developer.yahoo.com/yui/3/event/#onavailable


Try this.

_x000D_
_x000D_
document.getElementById("div").onload = alert("This is a div.");
_x000D_
<div id="div">Hello World</div>
_x000D_
_x000D_
_x000D_

Try this one too. You need to remove . from oQuickReply.swap() to make the function working.

_x000D_
_x000D_
document.getElementById("div").onload = oQuickReplyswap();_x000D_
function oQuickReplyswap() {_x000D_
alert("Hello World");_x000D_
}
_x000D_
<div id="div"></div>
_x000D_
_x000D_
_x000D_


I am learning javascript and jquery and was going through all the answer, i faced same issue when calling javascript function for loading div element. I tried $('<divid>').ready(function(){alert('test'}) and it worked for me. I want to know is this good way to perform onload call on div element in the way i did using jquery selector.

thanks