2

is something like this possible?

<div id="box1" onload="$("#box1").addClass("fadeIn");"></div>

The script does not seem to run when the document loads. I know that declaring a function beforehand and then using it on load works like below. Are you able to write javascript/jQuery instead of a function like I have tried above?

<div id="box1" onload="myFunction();"></div>

Games Brainiac
  • 80,178
  • 33
  • 141
  • 199
EHerman
  • 1,852
  • 7
  • 32
  • 52

4 Answers4

4

Try adding to the document ready:

$(document).ready(function () {
    $("#box1").addClass("fadeIn");
});

There may be other ways to do it, but from what I've found this is probably the most reliable.

valverij
  • 4,871
  • 1
  • 22
  • 35
0

Do it dynamically using the .ready() method (docs) or using the .on() method (docs). The ready method will execute the code as soon as the DOM is ready. The onload will execute as all assets are loaded (images for example).

$('#box1').ready( function() {
  ...
} );

//--or--

$( document ).ready( function() {
  $('#box1').on( 'load', function() {
    ...
  }
}
Sumurai8
  • 20,333
  • 11
  • 66
  • 100
0

It may or may not work. When Your browser run every onload, jQuery may not been initialized. Better use jQuery directly in <script>.

Radosław Miernik
  • 4,004
  • 8
  • 33
  • 36
0

DIV elements do not have an onload event. But knowing when the element is loaded is easy, since the browser loads the DOM synchronously.

Just put the script right after the closing tag and it’s done:

<div id="box1"></div>
<script>$("#box1").addClass("fadeIn");</script>
David Hellsing
  • 106,495
  • 44
  • 176
  • 212