-1

So I have a new button that is written by JavaScript when the users clicks on the + button.

However it seems that the new button can not access the JavaScript click function.

I am wondering how do I fix this.

JS

$('div.btn-floating').click(function () {
 //alert(this.id);
 if(this.id === "addnew"){  

 dl= document.getElementById("newpetprofiles");
dl.insertAdjacentHTML('afterbegin','<div class="btn-floating btn-large blue waves-effect waves-light"><img src="https://ipet.xyz/template/images/russellharrower.jpg"/></div>');

 }

  var morphFAB = $('#overlay');
  morphFAB.toggleClass('visible hidden');
  if (morphFAB.hasClass('visible')) {
    $('#form').addClass('animated slideInUp');
  }else {
    $('#form').removeClass('animated slideInUp');
  }
})
RussellHarrower
  • 6,470
  • 21
  • 102
  • 204

1 Answers1

1

The .Click function iterates the dom for all matching elements and adds an event handler for those elements. At the time this occurs, your dynamically created button doesn't exist. Therefore no event handler is attached. You need to use jQuery.on

Change:

     $('div.btn-floating').click(function () {

To

     $(document).on("click", "div.btn-floating", function () {

This will continually search for all matching elements and adds an event handler when they are appended to the document. The best solution would be to use the closest common parent instead of document. Like so:

    $("<my common parent element>").on("click", "div.btn-floating", function () {
S. Walker
  • 2,129
  • 12
  • 30