Event is not tied to the element

Asked

Viewed 704 times

13

I have an event at jQuery (version 1.5) as follows::

 $('#refresh_abertos').click(function(){
      // aqui o código irrelevante nesta pergunta     
 });

Turns out my element #refresh_abertos is only loaded later via ajax, and the .click() don’t get tied to it, how can I fix it?

5 answers

13


Problem

By the time your code is being read, your element does not exist on the page, so the attachment of the click never occurs.

Solution

As an alternative to what has already been suggested, if you intend to attach an click to an element that does not yet exist yet, can attach the same to an element that is parent, as is the case with body or a wrapper which is present on the home page of the page.

Practical Example

Example in Jsfiddle

In the example I used setTimeout to simulate the insertion of an element in the DOM a bit after reading the page.

I don’t know yours Markup, by which remains an example assuming that your element #refresh_abertos will be placed within a div containing the ID #myWrapper:

$('#myWrapper').on("click", "#refresh_abertos", function() {
    alert("bubu");
});

What we’re doing here is attaching the event of click in div#myWrapper to be triggered when it has an effect on the #refresh_abertos.

So you get the click a parent element that will take effect when you click on the input element.


The solution presented makes use of jQuery .on() available as of version 1.7.

  • There have been other responses like this, plus @Zuul was the first to indicate using a parent div of the element, which in this case is the most ideal, so I’m accepting your answer as correct.

8

The best solution I see is to delegate the click via Document (or a relative who has been present since the page uploaded).

So you can use:

 $(document).on('click','#refresh_abertos',function(){
      // aqui o código irrelevante nesta pergunta     
 });

Using the .on() you can have the "Handler" applied to document (a secure letter, as said could be another relative), but delegated to #refresh_abertos

For versions prior to jQuery 1.7 can be used .delegate() in time of .on()

  • It is also possible to use .live besides .delegate (although do not know if there is significant difference in performance)

  • 1

    @mgibsonbr took a look here and I thought it best to suggest .delegate()

6

Assuming you’re using a function like the jQuery.load(). Add the code to callback event, that is, a function that jQuery performs to conclude both the request and the update of the DOM.

Take an example:

$("#local_carregamento").load("ajax/pagina.html", function() {

   $('#refresh_abertos').click(function(){
      // aqui o código irrelevante nesta pergunta   
   });

});

And one more example using the function jQuery.ajax():

$.ajax("example.php")
  .done(function() {
     $('#refresh_abertos').click(function(){
        // aqui o código irrelevante nesta pergunta   
     });
  })
  .fail(function() {
    alert( "error" );
  })
  .always(function() {
    alert( "complete" );
  });

Note that, according to the documentation, the callbacks success, error and complete are depreciated as of version 1.8.

  • I actually use the $.ajax really, I’ll put in the success.

  • @Kennyrafael Okay, I’ve added one more example to make the answer complete. Also, if you use jQuery 1.8 or higher, consider using callback done, as an example.

  • In this project I use version 1.5, never used this syntax you put, it serves for this version also?

  • 1

    @Kennyrafael Is there any specific reason to use such an old version? If it is possible to upgrade, upgrade, this will even make your system more compatible with most browsers (present and old).

  • @Kennyrafael My example will not server for you. In your case it has to be the 3rd parameter as in the examples of other answers. And as mentioned, try to update the version... ;)

  • Unfortunately I cannot update the version...

Show 1 more comment

6

You can use the method .live (in newer versions of jQuery, .on):

$("#refresh_abertos").live("click", function() { ... });

Example in jsFiddle. Citing the documentation of live (my emphasis):

Places an event handler for all elements matching the selector used, now and in the future.

Note: the method live is obsolete from the version 1.7, being the on the preferred way:

$("body").on("click", "#refresh_abertos", function() { ... });

Example. The advantage of on is that he places Handler not in the element itself, but in some ancestral element (in this example I chose the body, but it could be another more restricted), and it reacts to events in any descending element that passes in the chosen filter (the second argument, a selector). In this way, elements added later are also contemplated, and without an excessive cost of performance (the live, if I’m not mistaken, you need to double-check the selector whenever an element is added to the DOM, anywhere on the page).

5

The simplest and most obvious solution I can imagine right now, quickly, is to make the "bind" after loading the element via AJAX. Look at API of the method you are using to make the request, make the bind in the Success that should work.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.