简体   繁体   中英

Run jquery Once content of a div has fully loaded

I have a div am-events-booking that is dynamically loaded using Javascript and this div normally takes a second or so to load after the page has loaded. I would like to run a jQuery code once the contents of this div has fully loaded.

Below is the workaround i have used to delay the running of the script by 5000ms however this doesn't seem to be correct as if the page load takes more than 5000ms then the script would not run. Is there are better way to do this? May be use mutations and if so, how do I go about it?

 jQuery(document).ready(function($) { $(document).ready(function() { var i = setInterval(function() { if ($("#am-events-booking").text().length > 0) { clearInterval(i); $(".am-event-data").addClass('bg'); } else { console.log("Waiting..."); } }, 5000); console.log("Page is loaded"); }); });
 .am-event-data { border: 1px solid black; padding: 10px; width: 50%; }.bg { background: red; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="am-events-booking"> <div class="am-event-data"> <div class="am-event-date"> <div class="am-event-date-month" style="color: rgb(249, 169, 126);">Mar</div> <div class="am-event-date-day">24</div> </div> <div class="am-event-info"> <div class="am-event-title">Ballet <span class="am-event-booking-status open">Open</span></div> </div> </div> <div class="am-event-data"> <div class="am-event-date"> <div class="am-event-date-month" style="color: rgb(249, 169, 126);">April</div> <div class="am-event-date-day">25</div> </div> <div class="am-event-info"> <div class="am-event-title">Other <span class="am-event-booking-status open">Open</span></div> </div> </div> </div>

Have you taken a look at jQuery.on('load')?

The following answer may help - https://stackoverflow.com/a/58871367/3907839

Alternatively, can you use something like this?

https://gist.github.com/chrisjhoughton/7890303#file-wait-el-js

So in your case, include the waitForEl function in your code and then use it. Take a read through the comments for relevant refactored code, I've just looked at the first bit.

waitForEl($("#am-events-booking"), function() {
    $(".am-event-data").addClass('bg');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM