jQuery, close button works only once

Asked

Viewed 292 times

1

I have a text box that is generated by a button, and it has a button with the function to close it, but it only works once, for the first generated box, I would like it to work on all that are generated later.

And in that I have another small bug, by completely removing the text and keeping pressed the Backspace the box shrinks and goes up to the menu.

https://jsfiddle.net/h6orx7x0/10/

1 answer

2


You have to use event delegation:

$('#editavel').on('click', "#close-link", function() {
    $('#close').fadeOut();
});

The problem is that when you run $("#close-link").click(function(){ this code will not catch elements that do not exist yet. But if you delegate to the element that always exists, the $('#editavel') will already work.

You can read more about it here: /a/5199/129

Note: Ids must be unique, that means you must only have 1 #close-link on the page. Otherwise you should use classes: .close-link

  • Excellent explanation, partly solved my problem, but I ended up expressing myself wrong. When I said "I would like it to work on all that are generated later." , I forgot to explain that it was in one at a time, using the syntax '.on' it erases all generated elements that have the same declared class, not just the one that was clicked. I imagine that it is more complicated to differentiate each generated element, but it is possible?

  • @Wesleyferreira so you want the close-link just erase the close" que estiver dentro desse ui-widget-contenté isso? Lembra-te de usar classes, mas o que queres pode ser feito assim:$(this). Closest(). find('#close'). fadeOut();`

  • Actually no, imagine that I manage several boxes, I need to specifically close one, for example the second. The problem is that the script closes everything that has the class . close (I’ve already turned it into class). https://jsfiddle.net/wesleyfc000/h6orx7x0/11/

  • @Wesleyferreira the answer I gave is what you’re looking for. In the last comment you missed writing something, the idea is: $(this).closest('.ui-widget-content').find('#close').fadeOut();. That way every click he’ll look for his father '.ui-widget-content.' of that element clicked, and then inside it, the element close. Switch to classes and it will work.

Browser other questions tagged

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