3

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.

kcc989
  • 33
  • 5

3 Answers3

2

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 */
});
76484
  • 8,498
  • 3
  • 19
  • 30
  • Thank you, this was very helpful. I did some digging in the JQuery docs but never stumbled upon this. This was exactly what I needed. – kcc989 Mar 24 '14 at 23:51
1

Delegate the click event to closest container for better performance.

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

});
Wilmer
  • 2,511
  • 1
  • 14
  • 8
0

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);
Ananthan Unni
  • 1,304
  • 9
  • 23