1

I can't get my jquery function to work even when I have two pieces of identical code.

Here is the primary jquery function (i've removed the "<").

$(".spoiler").append("<button> Reveal Spoiler!</button>");
$(".spoiler button").click(function() {
    $(this).remove();
});

This creates a button that is then removed when it is clicked.

Now when I do this:

$("#family-question").click(function(){
    $("#answer-one").append("<button> Answer One </button>");
    $("#answer-two").append("<button> Answer Two </button>");
    $(".test").append("<button> Answer Three </button>");
});

$(".test button").click(function() {  
    $(this).remove();
});

This creates all the buttons. However if I click the button it isn't removed.

In terms of the HTML code. first one is;

<p class="spoiler">
    <!--Spoiler:-->
    <span>Darth Vader is Luke Skywalker's Father! Noooooooooooo!</span>
</p>

The second one has an ID as well as a class;

<p class="test" id="answer-one">
  <span>Answer Option one</span>
  </p>

Why doesn't it work?

j08691
  • 190,436
  • 28
  • 232
  • 252

1 Answers1

2

.test button element does not exist until you append it. Instead, you should add the click event once the button is appended:

$("#family-question").click(function(){
   $("#answer-one").append("<button> Answer One </button>");
   $("#answer-two").append("<button> Answer Two </button>");
   $(".test").append("<button> Answer Three </button>");
   $(".test button").click(function() { // button exists now!
     $(this).remove();
  });
});

Edit:

An even better way to do this is to use delegation. This means that when the specified element is clicked, the click event will see if there is a 'button' child within the bound element and pass the click event to that button element:

$(".test").on('click', 'button', function () {
   $(this).remove();
});

The benefit to this is that you only have to bind the event once and the button does not even have to exist yet.

KJ Price
  • 5,368
  • 2
  • 16
  • 33
  • Can I ask too. does this create any loading issues as the function would remain open until the second function is called? – markthewizard1234 Apr 03 '15 at 20:04
  • 2
    You should use event delegation instead of nested click binding. This will add redundant click handlers every time you click on #family-question which will degrade performance unnecessarily. – j08691 Apr 03 '15 at 20:08
  • Ah, good point @j08691. – KJ Price Apr 03 '15 at 20:14