Sunday, 18 August 2013

Javascript- code getting executed before all elements are ready.

Javascript- code getting executed before all elements are ready.

I have this code in my web. This page takes multiple image files as input
and displays them before uploading them to server.
<html>
<script type="text/javascript" src="jquery-1.9.1.min.js"></script>
<body>
<header>
<h1>File API - FileReader</h1>
</header>
<label for="files">Select multiple files: </label>
<input id="files" type="file" multiple/>
<div id='10' style=" width:100px; height:50px;
background-color:#006633" onclick="submit_rr(event)">Click</div>
<output id="result" />
</body>
<script language="javascript" type="text/javascript" >
function submit_rr(event){
$('#files').click();
}
$("#files").change(function(){
show_selected(this);
});
function show_selected(input){
for(var i = 0;i< input.files.length; i++) {
var reader = new FileReader();
reader.readAsDataURL(input.files[i]);
reader.onload = function (e) {
var img = new Image;
img.onload = function() {
if(img.width>=img.height){
ratio=img.height/img.width;
height=ratio*100;
height_rem=(100-height)/2;
var crt=document.createElement('div');
crt.id="main_some";
crt.className="ind_req_sty";
var Friend="Friend";
crt.innerHTML="<img id="+i+" width='100px'
height='"+height+"px' src='"+e.target.result+"'/>";
document.getElementById('10').appendChild(crt);
}else{
ratio=img.width/img.height;
width=ratio*100;
var crt=document.createElement('div');
crt.id='main_req';
crt.className="ind_req_sty";
var Friend="Friend";
crt.innerHTML="<img id="+x+" height='100px'
width='"+width+"' src='" + e.target.result
+"'/>";
document.getElementById('10').appendChild(crt);
}
}
img.src=reader.result;
}
}
}
</script>
</html>
Problem is that, this script executes before all the elements are
displayed. As a result only few images are displayed(say 4 out of 10
selected). I tried adding .ready() and .load() but that doesn't work.
However if I add an alert('something') all images are displayed without
any issue. is there a way I can delay execution so that all images are
loaded. I have also tried setTimeout() without any luck. Thanks for your
help

No comments:

Post a Comment