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.

3
  • stackoverflow.com/questions/8752321/… Commented Mar 24, 2014 at 21:47
  • Last line of code should say: $(course).empty(); Commented Mar 24, 2014 at 21:50
  • Yes it should, thanks for that. Commented Mar 24, 2014 at 23:43

3 Answers 3

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 */
});
Sign up to request clarification or add additional context in comments.

1 Comment

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.
1

Delegate the click event to closest container for better performance.

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

});

Comments

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);

Comments

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.