Home > Net >  jQuery 3.6.0 onload seems to be not working
jQuery 3.6.0 onload seems to be not working

Time:02-21

I have used jQuery v3.6.0. It seems to not working.

I want to fade out the class(alert) after a few seconds when the class (alert) loads.

$(document).ready(function() {
        $(".alert").on("load", function() {
            setTimeout(function() {
                $(".alert").fadeOut();
            }, 3000);
        });
    });

I have used the following code, but it seems to be not working. Is there any problem in my code. Please Help Me To Sort It Out

CodePudding user response:

EDIT:

There is no need to have a load() for this class (.alert). This is because your setTimeout() function will only run once the DOM is loaded because you are using the $(document).ready() method. Everything inside the $(document).ready() will only run once the DOM has loaded (including the .alert class).

You can remove the additional load function completely and this will work :)

But please be reminded of this in the docs for $(document).ready():

  • $( handler )
  • $( document ).ready( handler )
  • $( "document" ).ready( handler )
  • $( "img" ).ready( handler )
  • $().ready( handler )

As of jQuery 3.0, only the first syntax is recommended; the other syntaxes still work but are deprecated. This is because the selection has no bearing on the behavior of the .ready() method, which is inefficient and can lead to incorrect assumptions about the method's behavior. For example, the third syntax works with "document" which selects nothing. The fourth syntax waits for the document to be ready but implies (incorrectly) that it waits for images to become ready.

console.log('DOM not loaded yet, so .alert is not ready');
// DOM is not ready yet here
$(document).ready(function() {
// DOM is ready, function will run
  console.log('DOM loaded, so .alert is visible - timeout will run');
  setTimeout(function() {
    $(".alert").fadeOut();
    console.log('.alert is now hidden');
  }, 3000);

});
.alert {
  display: block;
  width: 75px;
  height: 75px;
  background: red;
}
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<div >

</div>

  • Related