0

How can I add a button and react to an outside onclick function? I need it available as well for the generated button and for static buttons that are on the site. At the moment I have the function twice to make it work for both kind of buttons, but that seems kind of redundant.

button.on("click", function() {
  banner.addClass("alt")
  $("<br><button class='test'>TEST</button><br>").insertAfter(button);

  //Here it works for the generated button:
  $(".test").on("click", function() {
    banner.removeClass("alt")
    banner.addClass("alt2")
  })

})

//Here it only works with the static buttons:
$(".test").on("click", function() {
  banner.removeClass("alt")
  banner.addClass("alt2")
})

https://jsfiddle.net/tdL3s4f8/

Tritol
  • 85
  • 1
  • 6
  • 1
    Possible duplicate of [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) –  May 29 '18 at 05:32

2 Answers2

1

Add your click listener to parent container element handle in following ways. I chose document as parent you can have it more specific.

$(document).on('click', '.test', function(){
    banner.removeClass("alt")
    banner.addClass("alt2")
})
Albert Einstein
  • 7,472
  • 8
  • 36
  • 71
Manoj
  • 1,175
  • 7
  • 11
0

You need to search static ancestors (parent) of the dynamically added element. And bind certain event based on that parent.

var banner = $("#banner-message")
var button = $("button")

button.on("click", function() {
  banner.addClass("alt")
  $("<br><button class='test'>TEST</button><br>").insertAfter(button);

  //This one works:
  //$(".test").on("click", function() {
    //banner.removeClass("alt")
    //banner.addClass("alt2")
  //})

})
//This one doesn't work:
$("#banner-message").on("click",".test", function() {
  banner.removeClass("alt")
  banner.addClass("alt2")
})
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#banner-message {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  font-size: 25px;
  text-align: center;
  transition: all 0.2s;
  margin: 0 auto;
  width: 300px;
}

button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;
}

#banner-message.alt {
  background: #0084ff;
  color: #fff;
  margin-top: 40px;
  width: 200px;
}

#banner-message.alt2 button {
  background: #000;
  color: #fff;
}

#banner-message.alt2 {
  background: red;
  color: #fff;
  margin-top: 40px;
  width: 200px;
}

#banner-message.alt button {
  background: #fff;
  color: #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="banner-message">
  <p>Hello World</p>
  <button>Change color</button>
</div>
Albert Einstein
  • 7,472
  • 8
  • 36
  • 71