This question has been asked a couple times but not answered in such a way that it can help me with my specific issue. From a nav list, on click of an item, I'm loading some HTML content into a div using the .html()
function. There is no ajax request. The HTML content has images. Hence it can take a moment to load up. And since .html()
is a synchronous operation, the next line will immediately execute.
As soon as I load contents using .html()
, I'm enabling a third party custom scrollbar called tinyscrollbar. If the loaded content had images, then the scrollbar calculates the height of the content div a little earlier than the images are loaded resulting into a scrollbar that won't scroll all the way.
I do not want to use .setInterval()
. Is there a solution for this? Is there some other function in jQuery that acts like the .html()
function but has some sort of callback feature?
Thank you.
jQuery Callback Functions JavaScript statements are executed line by line. However, with effects, the next line of code can be run even though the effect is not finished. This can create errors. To prevent this, you can create a callback function. A callback function is executed after the current effect is finished.
A callback is a function passed as an argument to another function. This technique allows a function to call another function. A callback function can run after another function has finished.
Description. The ajaxSuccess( callback ) method attaches a function to be executed whenever an AJAX request completes successfully. This is an Ajax Event.
A callback function is a function that is passed as an argument to another function, to be “called back” at a later time. A function that accepts other functions as arguments is called a higher-order function, which contains the logic for when the callback function gets executed.
$('#divId').html(someText).promise().done(function(){ //your callback logic / code here });
Based on Mike Robinson's (and dystroy's) suggestion the answer to my question is:
$("#myContentDiv").html('HTML content comes here'); var contentImages = $("#myContentDiv img"); var totalImages = contentImages.length; var loadedImages = 0; contentImages.each(function(){ $(this).on('load', function(){ loadedImages++; if(loadedImages == totalImages) { $("#myContentDiv").tinyscrollbar(); } }); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With