drugsrbad
drugsrbad

Reputation: 59

setting onclick event to dynamically added button?

I wanna ask how to assign the onclick event to a dynamically added button on DOM? For example, after creating the button by the following

var btn = document.createElement("button");

I want to create the onclick for this button so that when I click on it, this will call the function purchase(json[i].id). How should I add to it?

Upvotes: 2

Views: 3562

Answers (2)

Tina
Tina

Reputation: 1234

In order for listeners to be added to buttons added programmatically, we need to attach the listener to the parent of the buttons rather than the buttons themselves.

Let's assume the HTML is as follows:

<div id="buttons">

  <button class="btn">
    Existing button
  </button>

</div>

We can use jQuery's .on method with event delegation.

This is using the .on method without delegation—it does not work:

$('.btn').on('click', handleClick); // don't use this, it won't work

This is using the .on method with delegation—this does work:

$('#buttons').on('click', '.btn', handleClick);

In order for this to work, there needs to be a common parent element for the original buttons and the buttons you'll be adding, as per the docs:

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, you can use delegated events to avoid the need to frequently attach and remove event handlers.

In my example, the new button will be added to the parent element #buttons programmatically after a 2 second timeout, and the click handler will still be attached because #buttons was there on page load.

When we attach a click handler to the buttons, we can't attach the click handler to a button that doesn't exist yet, but if we attach to the parent of the buttons that exists from the start, when new buttons are added they will have click listeners attached:

var $buttons = $('#buttons');

var handleClick = function () {
  alert('Button click works!');
};

// Works for new buttons (uses event delegation)
$buttons.on('click', '.btn', handleClick);


// Add a new button after 2 seconds
setTimeout(function () {
  var $newButton = $('<button />');

  $newButton
    .addClass('btn')
    .text('New button');

  $buttons.append($newButton);
}, 2000);

If you need the purchase ID, you can store it on a data attribute like this:

  <button class="btn" data-purchase="purchase_01">
    Existing button
  </button>

Then, in the JavaScript you can access it like this in the handler:

var handleClick = function () {
  var purchaseId = $(this).data('purchase');

  alert('Button click works! \n\n' + purchaseId);
};

A working demo where you can toggle event delegation is available here: http://codepen.io/tinacious/pen/MbQJWX?editors=1010

Upvotes: 5

grzesiekgs
grzesiekgs

Reputation: 463

var button = document.createElement('button')

button.addEventListener('click', function(event) {
 ... your code here ...
})

someContainerElement.appendChild(button)

The method names pretty much explain what is going on, but to be explicit:

First, create a button tag and assign it to the button variable

var button = document.createElement('button')

Add an event listener to the button element. It listens for the click event, and fires the function.

button.addEventListener('click', function(event) {
  ... your code here ...
})

Then append your button to someContainerElement. This means that your button will be placed inside this parent element.

someContainerElement.appendChild(button)

Upvotes: 0

Related Questions