Abdullah Awan Abdullah Awan - 5 months ago 17
jQuery Question

JQuery function .load not working

I have the next code. What am trying to do is when i refresh or open the page, to add the class intro. But my main problem is in the part :

$("body").load(function(){


I want when the page is opened, then to add the class
.intro
. Instead of body, i have also tried html, and still doesn't work.



<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("body").load(function(){
$("p").addClass("intro");
});
});
</script>
<style>
.intro {
background-color:green;
}
</style>
</head>
<body>

<img src="https://k32.kn3.net/taringa/1/9/3/9/4/7/32/johnny_te_toco/330x330_248.gif" width="304" height="236">

<p><b>Note:</b> Depending on the browser, the load event may not trigger if the image is cached.</p>

</body>
</html>




Answer

Try this instead:

$(document).ready(function(){
    $(window).load(function(){
         $("p").addClass("intro");
    });
});

Load event attached to the window. If that is what you meant? Load on a DOM element like that doesn't make much sense.

Whilst this should work, you could pull it out of your ready() event.

$(document).ready(function(){
    // Nothing to see here...
});

$(window).load(function(){
    $("p").addClass("intro");
});

This waits for the load of the window, but if you just want to add the class as soon as possible when the DOM is ready, well, you won't need the load() at all:

$(document).ready(function(){
    $("p").addClass("intro");
});

Bonus: You should use on() to attach all events going forward.

$(window).on('load', function(){
    $("p").addClass("intro");
});

on() is the preferred method for events in future jQuery versions, as older methods are deprecated.

All the best.

Comments