Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery event after html() function

Is there a way to launch an event after html() has been fired? Such as:

$.post("ajax.php", {data :data}, function(data){
   $("#countries").html(data, function(){
      alert("test");
   });
});

This is not working.

EDIT: I am asking this because I want to do few things(another call) with the information coming from the call... I wanted to simplify the example...I guess programmers always want to know why...

So here it is the example updated

 $.post("ajax.php", {data :data}, function(data){
   $("#countries").html(data, function(){
        var id = $("#countries option:selected").attr("id");
        getRegions(id);
   });
});
like image 521
Alfonso Fernandez-Ocampo Avatar asked Aug 06 '12 10:08

Alfonso Fernandez-Ocampo


2 Answers

Yes you can...

// create a reference to the old `.html()` function
var htmlOriginal = $.fn.html;

// redefine the `.html()` function to accept a callback
$.fn.html = function(html,callback){
  // run the old `.html()` function with the first parameter
  var ret = htmlOriginal.apply(this, arguments);
  // run the callback (if it is defined)
  if(typeof callback == "function"){
    callback();
  }
  // make sure chaining is not broken
  return ret;
}

// test it all works as expected (including chaining)
$("#mything").html("<div>My Thing</div>",function(){
  console.log("Just did my thing");
}).css({color: 'red'})

However, like everyone else says, it is unnecessary as .html() is synchronous, so you can just put your code following it rather than in a callback.

Demo: http://jsfiddle.net/billymoon/a49P4/

like image 52
Billy Moon Avatar answered Sep 21 '22 13:09

Billy Moon


html() is a synchronous operation, not an event, and so it would not logically accept a callback.

Just put your code after it:

$('container').html(data);
alert('test');
like image 36
Mitya Avatar answered Sep 21 '22 13:09

Mitya