0

I am trying to append a div with a button so that when when it is clicked I can execute a function.

I am currently appending a div like this.

$('.window').append('<div class="message messageUser2"><div class="bubble bubbleUser"><p class="chatText"><div class="chat-input"><textarea type="text" class="inputChatText" id="message" name="message" placeholder="enter your message" data-required/></div></p><img type="button" class="test" src="img/up.png"></img></div></div>');

It appends and everything looks right on the page but when I click the button/img nothing happens. For starters i'm just trying to console log the click but eventually want a function to run but cant do this until its clickable.

$('.test').on('click', function() {
console.log("The test button was clicked");
});  

As you can see here its appending even according to the console

Anyone have any ideas of what I need to do to actually get this to be a clickable event after I append it? Thanks

Barmar
  • 741,623
  • 53
  • 500
  • 612
rubydanger
  • 11
  • 1
  • What do you expect to happen when you click the button/img? It's logging to the console. http://codepen.io/anon/pen/YNbYOO – Michael Coker Feb 18 '17 at 01:24
  • Trying to use it to submit the information in the text area. Mine shows nothing when clicked in the console. – rubydanger Feb 18 '17 at 01:30
  • your question was closed. you might try changing the click handler to `$(document).on('click', '.test', function() {` – Michael Coker Feb 18 '17 at 01:33
  • Yup, the thing here is changing the object you attach your listener to. Your button do not exist when scripts are loaded, so your eventListener don't have the element to which it can attach to. $(document).on('click', '.test', function() {}) fixes the problem, its attached to document, but filters only to element with test class – Przemek Lewandowski Feb 18 '17 at 01:36

0 Answers0