0

How to add onload event to a div element points out that the onload attribute only works for <body> and external sources (like <script>).

So for the example in that question:

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

the onload contents will never be called.


How can I trigger some javascript to run when a div is added to the page, via the div element HTML itself?

As we've seen

$('<div onload="myFunction()"></div>').appendTo('body');

Won't work. myFunction will not be called, because onload isn't even triggered for divs.


I am creating HTML on the backend using C# Razor/DevExtreme, and it doesn't load the entire webpage at once but I want to run some code after some part of the webpage has loaded. This is why i can't just

$('<div></div>').appendTo('body');
myFunction();
theonlygusti
  • 11,032
  • 11
  • 64
  • 119
  • `appendTo` is immediate. Is there a reason you can't just do `$('
    ').appendTo('body'); myFunction()`?
    – edemaine Jul 27 '21 at 15:21
  • @edemaine yeah, I am not the one doing the injecting – theonlygusti Jul 27 '21 at 15:21
  • 3
    You cannot trigger an event using only the markup inside the inserted element. You'll need to have the trigger in place before inserting. Try document.addEventListener('DOMNodeInserted', myFunction): https://stackoverflow.com/questions/9778962/handler-for-dynamically-created-dom-nodes-as-they-are-inserted (of course, you'll need to filter for the nodes of interest -- here you _can_ insert some markup into the new DOM node that you then can use as a filter criterion in myFunction). – orithena Jul 27 '21 at 15:26
  • 1
    @orithena looks like the best workaround, thanks – theonlygusti Jul 27 '21 at 15:30

1 Answers1

0

Most elements don't load anything, they just are.

To do something after you add a DIV to the DOM, just do that thing on the next line of code:

$('<div onload="myFunction()"></div>').appendTo('body');
console.log("The div will be in the DOM now");
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335