0

I am trying to implement a previous button on a test app. I cant get button id="prev" to fire. I am keeping it simple like this:

//Begin Previous Button Click Function
  //
  $("#btn2").click(function() {
      alert("i'm in previous button click");
  });
  // End of Previous Click Function

Here is the jsfiddle I get nothing in the console and setting a break point in function does not get called when stepping thru program. I checked the DOM to make sure btn2 was there and it is. Any suggestion appreciated.

Alan
  • 1,067
  • 1
  • 23
  • 37
  • Possible duplicate of [Event binding on dynamically created elements?](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – David Jan 27 '16 at 17:01

3 Answers3

1

Currently what you are using is called a "direct" binding which will only attach to element that exist on the page at the time your code makes the event binding call.

As you are creating elements dynamically. You need to use Event Delegation using .on() delegated-events approach, when generating elements dynamically or manipulation selector (like removing and adding classes).

General Syntax

$(staticParentElement).on('event','selector',callback_function)

Example

$('#div2').on('click', '#prev', function(){ 
     //Your code
});
Satpal
  • 132,252
  • 13
  • 159
  • 168
  • Thanks I will read up on event delegation and let you know how it turns out. Thanks to everyone for answering... – Alan Jan 27 '16 at 18:46
  • Reading up I have one question. I thought event handler was bound on first click. But now it seems it is on page load,yes? – Alan Jan 27 '16 at 22:03
0

Your question doesn't seem to make sense - if you want the item with id="prev" to fire, then your selector should be;

$("#prev")

not

$("#btn2")
Matthew Lymer
  • 992
  • 6
  • 10
0

The element doesn't exist when the document is ready, because you inserted it after to the DOM.

Try with this instance:

$(document).on("DOMNodeInserted", function() {
    // Call your prev button function or insert the code here
});
Ravenous
  • 194
  • 1
  • 5