kcc989
kcc989

Reputation: 33

Adding Click Function to Dynamically Generated div jquery

I am fairly new to JQuery and I am having issues with binding functions to a dynamically generated div.

Essentially the user clicks a button which adds a couple divs to a container and also changes the background color of that container. I want them to have the option to remove what they added by clicking on one of the divs.

I have this function that I thought should do that:

$('.course-delete').click(function() {
    var course = $(this).parent();
    alert("hello");
    $(course).css('background', "#fff");
    $(course).empty();  
});

But for whatever reason nothing happens when I click the div. If anyone knows what is going on I would appreciate it.

Upvotes: 3

Views: 1770

Answers (3)

Wilmer
Wilmer

Reputation: 2511

Delegate the click event to closest container for better performance.

$("#divcontainer").on("click", ".course-delete", function() {

});

Upvotes: 1

Ananthan Unni
Ananthan Unni

Reputation: 1304

You could also..

//Create your new DIV
var newDiv=$('<div />',{
html:'This is sample HTML', // add your HTML
click:function(){
// your click event handler
}
});

and then add to your document like...

newDiv.appendTo('body');//or any selector you want to append to. Use prependTo if you want it as the first element of the container.

So when combined, you can write like this...

$('<div />',{// you can set attributes and other stuff here
    html:'This is sample HTML', // add your HTML
    click:function(){
    // your click event handler
    }
 }).appendTo(container);

Upvotes: 0

76484
76484

Reputation: 8993

By the sounds of it, your .course-delete elements don't exist when jQuery attempts to bind the handler - because your divs are created dynamically later. If this is the issue, then event delegation will be your saviour: https://learn.jquery.com/events/event-delegation/

$(document).on('click', '.course-delete', function () {
    /* do delete stuff here */
});

Upvotes: 2

Related Questions