Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery html() callback function

Tags:

html

jquery

image

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.

like image 819
walmik Avatar asked Apr 24 '12 15:04

walmik


People also ask

What is jQuery callback function?

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.

What is callback () in JavaScript?

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.

What is AJAX callback function?

Description. The ajaxSuccess( callback ) method attaches a function to be executed whenever an AJAX request completes successfully. This is an Ajax Event.

What is callback function and how it works?

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.


2 Answers

$('#divId').html(someText).promise().done(function(){     //your callback logic / code here }); 
like image 180
Deb Avatar answered Oct 05 '22 17:10

Deb


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();             }         });     }); 
like image 37
walmik Avatar answered Oct 05 '22 16:10

walmik