Question

I appended a button to a div box, but I cannot apply a click functionality to the new button. In the given example I want to change the color of the div box through a button click.

js fiddle

HTML

<ul id="box"></ul>
<button id="add" type="button">Add button!</button>

jQuery

$("#add").click(function() {

    $("#box").append(' <button class="color" type="button">change color!</button> ');
});


$(".color").click(function(){
    $("#box").css("background","red");
});
Was it helpful?

Solution

jsFiddle DEMO

This is a classic case of event delegation. Since you created the button dynamically using jquery, the click event you've written won't fire. You have to handle as below using .on()

Use,

$(document).on('click', '.color', function() {
    //Do something
});

Note: Using document as the parent is bad in most cases & it affects performance because this event searches throught the whole document for the required class color. So, replace document with the closest parent which is always present in the DOM (static). May be in your case it is $('#box)

$('#box').on('click', '.color', function() {
    //Do something
});

OTHER TIPS

You can use a live delegation for this:

$("#box").on('click', '.color', function(){
    $("#box").css("background","red");
});

When the page loads, there is no element with class .button so there is no event binded to that element. with .on() it will bind live to the element.

jsFiddle

Proper creation solves the issue with delegation :

$("#add").click(function() {
    var button = $('<button />', {
        'class': 'color',
        type   : 'button',
        text   : 'change color!',
        on     : {
             click: function() {
                   $("#box").css("background","red");
             }
        }
    });

    $("#box").append(button);
});

FIDDLE

to delegate instead, and keep using the strings, do:

$('#box').on('click', '.color', function() {
    $("#box").css("background","red");
});

you have use the event delegation to apply events to the dynamically created elements

try this

$("body").on("click",".color",function(){
    $("#box").css("background","red");
});

here is the fiddle http://jsfiddle.net/AfUZS/6/

Is not possible to add any event to html which is not added in DOM Step 1: add button to DOM Step 2: add click event to the button

$("#add").click(function() {
    var newButton = $('<button class="color" type="button">change color!</button>');
    $("#box").append(newButton);
    newButton.click(clickNewBtn)
});

function clickNewBtn(){
    $("#box").css("background","red");
}

http://jsfiddle.net/AfUZS/5/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top