0

I have added a button dynamically. But when I click it, it fires multiple click events and calls the associated function with alert('clicked'); several times and not just one time.

Can you tell me why and how I can fix it?

Code

 var root = document.getElementById('current_page');
 var button = document.createElement('input');
 button.type = 'button';
 button.title = 'Add new book to list';
 button.className = 'btn btn-primary';
 button.id = 'get_new';
 button.setAttribute('value', 'No Thanks,Get New');
 button.setAttribute('style', 'position:relative; top:-5px;left:900px');
 root.appendChild(button);

Handler

$('body').on('click', '#get_new', function () {
            alert('clicked');
});
17
  • 1
    So... what's your question? Commented Jan 22, 2014 at 17:33
  • 3
    I guess he asks why the function with alert('clicked'); is fired more than once on a single click. Commented Jan 22, 2014 at 17:34
  • how to make it just to fire single click event.. Commented Jan 22, 2014 at 17:34
  • 1
    Only once for me jsfiddle.net/M23Xv. We need all the code to be able to verify why it isn't working. Or atleast a fiddle reproducing the error. Commented Jan 22, 2014 at 17:42
  • 2
    @josh sometimes it does not work on dynamically created elements... Commented Jan 22, 2014 at 17:44

1 Answer 1

1

Since you're already using jQuery, you may as well create the element using jQuery and bind the click function on its creation. This will likely solve whatever is causing your double-firing issue.

Fiddle: http://jsfiddle.net/f9PX4/

function myFunction() {
    alert('clicked');
}

$(function() {
    var button = $("<input>");
    button.attr("type", "button")
        .attr("title", "Add new book to list")
        .attr("id", "get_new")
        .css({ position: "relative", top: -5, left: 900 })
        .val("No Thanks,Get New")
        .addClass("btn btn-primary");
    button.click(function() {
        return myFunction();
    });
    $("#current_page").append(button);
});
Sign up to request clarification or add additional context in comments.

1 Comment

This is not necessary. The OP's code actually works fine, and uses delegation which is a good practice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.