javascript - How can I call a function after appending an element using jquery? -


i have thumbnails on page. when click on 1 of those, view original photo in jquery dialog. and, set width of dialog box dynamically based on photo width. so, have written following scripts it. however, looks can't access image newly appended div. below function wrote:

 function showorignalphoto($photo_name){      $('#image_frame img').remove(); //remove previous image       $('#image_frame').append('<img src="../image_path/'+$photo_name +'" />'); //append new image       $width = $('#image_frame img').width(); //get width of new image      alert($width); //return 0!!        $( "#dialog" ).dialog( "option", "width", $width); //set width of dialog box       $( "#dialog" ).dialog( "open" ); //open dialog }  

it able newly added element code not run 2 reasons.

  1. if dialogbox hidden display:none css , calculation of or children's height or width return 0 display none means height =0 , width = 0 .

  2. image takes time load . jo after adding on dom can't calculate height. in case calculative dimension using parent or have defined on css.

try this.

 function showorignalphoto($photo_name){      $('#image_frame img').remove(); //remove previous image       //show loading image before image loaded.        var img=$('<img class="thumbnail" src="../image_path/'+$photo_name +'" />');       img.on('load',function(){             //hide loading image after image loaded.             var width = this.width;             console.log(width);             $( "#dialog" ).dialog( "option", "width", width); //set width of dialog box         });        $( "#dialog" ).dialog( "open" ); //open dialog  } 

it take care of both problem.

  1. its putting on event callback called after dialog open statement .

  2. you image ready before calculating width.

you should give minimum width , height on dialog box until image loaded should gain width , height. plus can show loading image before image loaded.


Comments

Popular posts from this blog

python - Subclassed QStyledItemDelegate ignores Stylesheet -

java - HttpClient 3.1 Connection pooling vs HttpClient 4.3.2 -

SQL: Divide the sum of values in one table with the count of rows in another -