kthornbloom
kthornbloom

Reputation: 3730

How to tell jQuery a content editable div has been updated

I want to use jQuery to select an item that has been added to an HTML5 content editable div. It doesn't work right now because the item wasn't present when the page was loaded. How do I tell jQuery that the div has been updated?

Please see this jsfiddle for test code: http://jsfiddle.net/kthornbloom/sjHYQ/

$(document).ready(function() {

<!-- This wont work on an image dragged into the div after page load -->
$('#editor img').click(function(){
    $(this).fadeOut();
});

});​

I have seen other questions about this, but none seem to apply to a content editable div.

Upvotes: 2

Views: 328

Answers (2)

sdespont
sdespont

Reputation: 14025

You need to use .on() JQuery function to attach event to element dynamically created

Here is an example (I use body as main container, but you need to be more specific) :

$("#editor").on({
    click: function (event) {    
        console.log('test')
       $(this).fadeOut();
    }
    },
    "img"
);

Here is the fiddle http://jsfiddle.net/sjHYQ/2/

Upvotes: 0

j08691
j08691

Reputation: 208032

Try:

$('#editor').on('click', 'img', function() {
    $(this).fadeOut();
});​

jsFiddle example

Since you're essentially binding a dynamic element, you need to use .on() to delegate the click event on the #editor element because there is no image within the editor div when the page is loaded.

Upvotes: 3

Related Questions