I am a beginner in programming. I am looking a way to reuse my Image preview JQuery Code in external file. I want to make a form which has multiple images in it and I want to preview all the images before submitting. My single image preview code is as follows:
$(function () {
Test = {
UpdatePreview: function (obj) {
// if IE < 10 doesn't support FileReader
if (!window.FileReader) {
// don't know how to proceed to assign src to image tag
} else {
var reader = new FileReader();
var target = null;
reader.onload = function (e) {
target = e.target || e.srcElement;
$("#preview").attr("src", target.result);
};
reader.readAsDataURL(obj.files[0]);
}
}
};
});
where preview
is the id of my image tag.
I am absolute beginner in programming so please guide me in step by step. Thanks
Define this way:
Call this way:
Or attach a function to the
prototype
as given by Jean-Paul:And call this way:
But instead of reinventing the wheel (from this answer), you can also use ready-to-go code such as this example which previews images upon load.