1

I want to do something simple, a page that has 0 buttons when loaded, then every click I add a button in a line. when I click any of these buttons it removes it.

I tried to

$(":button").click(function(){
})

but it cant seem to get the button that have been clicked, if I start the page with these buttons already in it , it works. am i missing anything ?

Satpal
  • 132,252
  • 13
  • 159
  • 168

1 Answers1

2

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.

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

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

Example

$(document).on('click', ":button", function(){
    //Your code
});

In place of document you should use closest static container.

The delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, we can use delegated events to bind the click event to dynamically created elements and also to avoid the need to frequently attach and remove event handlers.

A good read Direct and delegated events

Satpal
  • 132,252
  • 13
  • 159
  • 168