I am working with JCrop jquery library, I am providing preview of image after uploading the file using HTML file control.
view part (demo data)
<input type="file" id="photograph" />
<img src="#" id="target" />
Javascript code
// for setting img src
function readURL(input) {
console.log("readURL");
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#target').attr('src', e.target.result);
console.log("inside if =>"+e.target.result);
}
console.log("outside IF");
reader.readAsDataURL(input.files[0]);
}
}
// for setting pre-selected cropping area
function setProperties(){
console.log("set properties");
$('#target').Jcrop({
setSelect: [0,12,23,43]
});
}
// on change event for fileupload
$("#photograph").change(function(){
console.log("change event called!");
readURL(this);
setProperties();
});
output
change event called!
readURL
outside IF
set properties
inside if=>data:image/jpeg;base64,/9j/4gIcSUNDX1BST0ZJTEUAAQEAAAIMbGNtcwIQAABtbnRyUkdC…sXK2t+4UdmuSVl64hb2gMHh1Nhm83DAdQJniIM6eZUxzuYCR2my3FSwGpVbzBdwlgrrc/
I want to set some properties after uploading the image file, but "inside if=>" [see the output posted above] is getting called at the very end. so why is this happening? and How should I tackle this issue?
You have to call setProperties
after image source
setted and image loaded
function readURL(input) {
console.log("readURL");
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#target').attr('src', e.target.result);
console.log("inside if =>"+e.target.result);
// Call after source setted and image file loaded
setProperties();
}
console.log("outside IF");
reader.readAsDataURL(input.files[0]);
}
}