You Are Here: Home » How-To » Programming

jQuery HTML() Callback Function Using Promise()

By Debjit on September 27th, 2014 
Advertisement

jQuery has a cool function called the html() which basically replicates the functionality of the innerHTML method in Javascript. Using HTML() with a jQuery object you can replace the contents of any container element like the <div> or <p>, <span> and others.

However, like other functions in jQuery, the html() function does not have a callback function. Which means you are unable to check or get a notification when the html() function has finished its work. This is where the promise() and the done() functions of jQuery come into picture.

You can implement a callback kind of functionality with the html() function in the following way:

    $('#divId').html(someText).promise().done(function(){
        //your callback logic / code here
    });

The promise() function used above basically returns an object when certain watch actions which might or might not have been queued get finished. jQuery .html is a good function and convenient at times however, I would recommend to use the native javascript innerHTML method in order to achieve whatever you are trying to do with jquery .html as the native innerhtml is faster!

Relying on jQuery for every other thing is not always great and you would be surprised to know that using native javascript many operations can be performed faster than using jQuery to do the same. I have also tried to remove jQuery once from WordPress, but later found out that is not a good idea.

Let us now take a look at some great examples of how you can use the above method to achieve various things.

1. Using the html() callback trick in jQuery to fire an ajax request after the target div has been populated with a result from the last ajax call's result as a part of its callback.

    $('#divId').html(someText).promise().done(function(){
        $.post('/target/url', {'callback' : 'jQuery'}, function() {

        });
     });

2. Various plugins such as Disquss comments or Facebook Javascript like buttons populate divs for loading their comments box of the like box. You can use this html() callback method to determine when these operations have completed and then, may be notify your users about specific events.

Please let me know if you found this tip helpful.

Advertisement







jQuery HTML() Callback Function Using Promise() was originally published on Digitizor.com on August 3, 2013 - 5:28 pm (Indian Standard Time)