1

I have a global javascript variable called "BTN":

var BTN;

When the user does certain things a function gets called which assigns a DOM-Button-element to this variable (via the following code):

BTN = document.createElement("BUTTON");
var text = document.createTextNode("click to remove me again");
BTN.appendChild(text);                

When the user clicks on the button, the button is supposed to disappear. To this end, I created the following Event-Listener:

$(BTN).on("click", function(){
    $(this).remove();
});

However, when I click on the button, nothing happens.

I don't understand what's wrong. The most ridiculous thing is this: clicking the button is not the only way the user can get rid of it. When he clicks a certain area, a function is called that (among other things) removes the button as well, simply by the following line of code:

if(BTN) $(BTN).remove();

This works like a charm. But the other method (where the user clicks on the button) does not work. I have no clue whatsoever how this can be!

steady_progress
  • 3,311
  • 10
  • 31
  • 62
  • Please provide a [mcve]. Are you sure you installed the listener on `$(BTN)` after you created it? – Bergi Jul 14 '17 at 18:16

2 Answers2

1

Since your button is added dynamically you can't bind an event directly to it because it doesn't exist yet. Try this example from the jQuery documentation to bind to the body instead of your button.

$( "body" ).on( "click", "ID of your button", function() {
    console.log( $( this ).text() );
});
0

Two suggestions:

  1. I don't think you need to wrap it in a jQuery object again... I think that this.remove(); (no $(this)) might work work?

  2. If that doesn't work, you could try adding a delay:

    $(BTN).on("click", function() {
        setTimeout($(this).remove, 10); // wait 10ms to remove this element
    });
    
Sumner Evans
  • 8,951
  • 5
  • 30
  • 47