Clément
Clément

Reputation: 33

Why is `onload=` event attribute not working on a `<div>` tag?

I don't know why the code got no error but isn't displaying the message in JavaScript in the mood function ! It's only displaying the div.

function mood() {
  var box = document.getElementById('t');
  document.getElementById('t').innerHTML = "Hey <strong>Thanks!</strong>";

}
<div onload="mood()" style="display: block" id="t">HEYYYYY</div>

Upvotes: 0

Views: 70

Answers (3)

James Ives
James Ives

Reputation: 3365

The onload attribute is only supported on the following HTML tags: <body>, <frame>, <frameset>, <iframe>, <img>, <input type="image">, <link>, <script> and <style>.

I've adjusted your example below, moving the onload attribute to the body tag in this instance.

function mood() {
  var box = document.getElementById('t');
  document.getElementById('t').innerHTML = "Hey <strong>Thanks!</strong>";

}
<body onload="mood()"> 
   <div id="t" style="display: block">HEYYYYY</div> 
</body>

Upvotes: 0

Electrox Mortem
Electrox Mortem

Reputation: 319

var box = document.getElementById('t');
function mood() {
  box.innerHTML = "Hey <strong>Thanks!</strong>";
}
window.addEventListener('load', mood)
<!DOCTYPE html>
<html>

<head>
  <title>MA page web</title>
  <script>
  </script>
</head>

<body>
  <divstyle="display: block" id="t">HEYYYYY</div>
</body>

</html>

You can use an event listener. This waits until the window is loaded and then runs the function. I hope this helps :)

Upvotes: 0

Spark
Spark

Reputation: 2487

Add the onload in body instead of div

<!DOCTYPE html>
    <html>
        <head>
            <title>MA page web</title>
            <script> 
            function mood(){
                var box = document.getElementById('t');
                document.getElementById('t').innerHTML = "Hey <strong>Thanks!</strong>";
            }
            </script>
        </head>
        <body onload="mood()">
            <div  style="display: block" id="t">HEYYYYY</div>

        </body>
    </html>

Upvotes: 1

Related Questions