0

I have 2 links:

<span id="a-start-container">
<a id="a-start" href="#">
<i class="fa fa-fw fa-play inner-circle-color"></i>
</a>
</span>

<span id="a-stop-container">
<a id="a-stop" href="#">
<i class="fa fa-fw fa-play inner-circle-color"></i>
</a>
</span>

When I click on the first one (a-start) I'm disabling it by removing the <a> element and at the same time I enable the second one (a-stop) by adding the <a> element:

$(document).ready(function() {
$("#a-start").click(function(e){
  $("#a-stop-container").html("<a id='a-stop' href=''><i class='fa fa-fw fa-stop inner-circle-color'></a>");
  $("#a-start-container").html("<i class='fa fa-fw fa-play inner-circle-color'>");
})
});

When I click on the second one (a-stop) I'm disabling it by removing the <a> element and at the same time I enable the first one (a-start) by adding the <a> element:

$(document).ready(function() {
$("#a-stop").click(function(e){
  $("#a-start-container").html("<a id='a-start' href=''><i class='fa fa-fw fa-play inner-circle-color'></a>");
  $("#a-stop-container").html("<i class='fa fa-fw fa-stop inner-circle-color-off'>");
  })
});

The problem is that it works only for the first click. For example I click on the first one (a-start), then it changes a-start and enables a-stop. But then, when I click on a-stop, JavaScript does not react anymore. The same situation the other way round. Both work fine until the <a> element gets changed - then I have to reload the page to get it run again.

There is no information in the console.

What am I doing wrong?

manifestor
  • 1,352
  • 6
  • 19
  • 34

1 Answers1

1

you should consider changing it to on instead of click based on the pattern that you are using. Usage of on can be found her: http://api.jquery.com/on/

What you are doing is replacing entire DOM content on which handler/listener is registered and thus it dont get re-registered on DOM change which is happening after first click event.

However what seemed like you only wanted to toggle class-name and text of the link which should have been handled via http://api.jquery.com/toggleClass/ which would be more appropriate.

Rikin
  • 5,351
  • 2
  • 15
  • 22
  • That's not enough information. You seem to imply that the OP should use event delegation, but that means `.on` has to be used in a specific way. Merely replacing `.click` with `.on` won't solve the problem. – Felix Kling May 04 '18 at 18:39
  • You were absolutely right, I changed it to `$("#a-start-container").on("click", "#a-start", function(e){}` and it works. – manifestor May 04 '18 at 19:08