0

Some handy functions like jquery html() setter has no callback. Is there a way to manually attach callback for them, such that you can for example add event listener only when the element is added to the DOM? I saw on the jquery documentation that

.html( htmlString )            Returns: jQuery

What exactly does it mean and is it relevant to what I want to achieve?

Naftali
  • 144,921
  • 39
  • 244
  • 303
spacemilkman
  • 943
  • 1
  • 9
  • 15
  • Are you in fact looking for something like `$('
    A
    ').appendTo(document.body).click(function(){console.log('hi')})` ? If not, your goal might be unclear.
    – Denys Séguret Jul 26 '13 at 17:35
  • Those functions are synchronous. – SLaks Jul 26 '13 at 17:36
  • [jQuery: How to listen for DOM changes?](http://stackoverflow.com/questions/9488653/jquery-how-to-listen-for-dom-changes) – dc5 Jul 26 '13 at 17:39
  • I do read that .html( htmlString ) is synchronous but that post seems to be dated so I would want to confirm. But other functions without callback can still be asynchronous? – spacemilkman Jul 26 '13 at 17:45

2 Answers2

2

DOM interaction is synchronous and returning the jQuery element is what most jQuery modifying methods (and plugins) do so that you can easily chain them. So once .html returns you can be sure that it is already in the DOM:

$(el).html( htmlString ).on('click', function() {});

Callbacks only make sense if you are performing an asynchonous operation (like making an AJAX request or waiting for an animation to finish).

Daff
  • 43,734
  • 9
  • 106
  • 120
1

When it says it return jQuery, that basically means it returns the jQuery object so you can chain methods. Like this:

$(".someElement").css("background, "green).html("Bananas");

To add event listeners to elements that are brought in dynamically you need to use event delegation.

You can't attach the listener straight on the element because it won't be ready to receive it. You need to instead, attach the listener to a parent element. This is called event delegation. You're delegating the job of handling the event to another element. Like so:

// Do this:
$(document).on("click", ".myNewElement", function() {
    //My event code in here
});

//Not this
$(".myNewElement").on("click", function() {});

The reason they return jQuery is so you can chain your methods like this:

$(".oldElement").html(".newElement").on("click", ".newElement", function(){});

You also might want to read up on $.Deffered.

Jonny Sooter
  • 2,417
  • 1
  • 24
  • 40