Languages
[Edit]
EN

JavaScript - add onload event to div

3 points
Created by:
Violetd
925

In this article, we would like to show you how to add onload event to div using JavaScript.

Quick solution:

You can't. However, you can add <script> tag performing some action right after the <div> to be executed immediately.

<div>Example text...</div>
<script type="text/javascript">
  // do something
</script>

 

Practical example

In this example, we get the element's offsetHeight property value right after the element is ready in the document body.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <div id="my-div">Example text...</div>
  <script type="text/javascript">

    var element = document.querySelector('#my-div');

    // do something on load e.g.:
    console.log(element.offsetHeight);

  </script>
</body>
</html>

 

References

  1. HTMLElement.offsetHeight - Web APIs | MDN
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join