Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I extend jQuery's replaceWith function to accept a callback function?

This should be easy, right? Yet I can't sem to find any examples of such a functionality anywhere. The problem is that after I do a replaceWith() I want to then do something with those elements that were written to the DOM, but if I try to do something to them right after the replaceWith() call they don't exist yet so I need to be sure the replaceWith() is completely finished. I just want something like this to work:

$('#foo').replaceWith('some text', function() {
     //do something else here
});

Thoughts?

like image 911
ocergynohtna Avatar asked Jan 26 '12 18:01

ocergynohtna


1 Answers

You can make your own function that calls replaceWith:

$.fn.replaceWithCallback = function(replace, callback){
    var ret = $.fn.replaceWith.call(this, replace); // Call replaceWith
    if(typeof callback === 'function'){
       callback.call(ret); // Call your callback
     }
    return ret;  // For chaining
};
like image 90
Rocket Hazmat Avatar answered Nov 09 '22 12:11

Rocket Hazmat