Dan Dan - 1 year ago 112
jQuery Question

Why won't my Jquery event fire on focusout()?

I'm trying to make a clean way to edit text on a page. When I double click on a

it needs to change the
to a text area with the text of the
in it.

Then when a user edits the text in the textarea and leaves it I would like to fire and event and save the contents of th textarea in the database via ajax. But my
event won't fire.

I tink it has to do with that I create the event handler first, then via
changes I change the
so that there is a textarea to fire the event from.

Here is my code:

//Edit text op de site
$('.textbox').dblclick(function(event) {
//Haal de benodigde id's op
var id = event.target.id;
var db_id = event.target.id.replace( /^\D+/g, '');

//Haal de contents van tussen de tags op
var tekst = $('#'+id).html();

//Replace de text met een textbox waarin de tekst wordt weergegeven
$('#'+id).replaceWith('<div id="text_' + db_id + '" class="textbox"><textarea id="textbox_aanpassen_' + db_id + '" class="textbox_aanpassen" maxlength="500"></textarea></div>');



$('.textbox_aanpassen').focusout( function(event){
var id = event.target.id;
var db_id = event.target.id.replace( /^\D+/g, '');


And the original
generated by

foreach($img as $key => $value){
$content .= '<div class="picture" id="'.$value['id'].'" style="background-image: url(../Storage/portfolio/'.$value['pic'].'); background-position: center;">';
$content .= '<div class="pencil" id="'.$value['id'].'">';
$content .= '<i id="'.$value['id'].'" class="fa fa-pencil fa-4x"></i>';
$content .= '</div>';
$content .= '<div class="slider">';
$content .= substr($value['titel'], 0, 12).' | '.$value['afmetingen'];
$content .= '</div>';
$content .= '</div>';

if($key == 2){
$content .= '<div id="text_'.$text[0]["id"].'" class="textbox">';
$content .= $text[0]["text"];
$content .= '</div>';
else if($key == 8){
$content .= '<div id="text_"'.$text[1]["id"].'" class="textbox">';
$content .= $text[1]["text"];
$content .= '</div>';

Answer Source

Because the DOM is changed dynamically use $(document).on('focusout', '.textbox_aanpassen', function(event){....

jQuery is only aware of the elements in the page at the time it runs, so new elements added to the DOM dynamically are unrecognized by jQuery. To combat the problem use event delegation, bubbling events from newly added items up to a point in the DOM whcih was there when jQuery ran on page load. Many people use document as the place to catch the bubbled event, but it isn't necessary to go all the way up the DOM tree. Ideally you should delegate to the nearest parent existing at the time of page load.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download