The image appears in the last position because your readURL
function is overwriting the .onload
property, storing only the last value (which points to #photo4
):
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
// You are setting the value of 'onload' property here...
reader.onload = function(e) {
$('#photo1').attr('src', e.target.result);
}
// Here, you overwrite the last value and store a new one...
reader.onload = function(e) {
$('#photo2').attr('src', e.target.result);
}
// Overwriting the last value and storing a new one...
reader.onload = function(e) {
$('#photo3').attr('src', e.target.result);
}
// This function will run when the load event of the reader fires
// as it's the last value stored in the property:
reader.onload = function(e) {
$('#photo4').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
Furthermore, each input type=file
element has the same id
, which is not recommended. All id
s should be unique.
To simplify your code, we can reduce it to this working version:
// Set up the same event handler for all input type=file elements
$(".file").on("change", function(e) {
if (this.files && this.files[0]) {
var reader = new FileReader();
// Use W3C DOM Event Standard for event listeners
reader.addEventListener("load", function(evt) {
// Set the src attribute of the next sibling element
e.target.nextElementSibling.setAttribute('src', evt.target.result);
});
reader.readAsDataURL(this.files[0]);
}
});
.col-md-4 {
width: 33.33333333%;
display: inline-block;
margin-bottom: 15%;
}
.labelav.largeFile:after {
...
}
.labelav.largeFile:hover:after {
...
}
.labelav.largeFile input.file {
visibility: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div class='col-md-4'>
<label class="labelav largeFile" for="file1">
<input type="file" id="file1" class="file img1" name="photo1">
<img id="photo1" src="#" alt="">
</label>
</div>
<div class='col-md-4'>
<label class="labelav largeFile" for="file2">
<input type="file" id="file2" class="file img2" name="photo2">
<img id="photo2" src="#" alt="">
</label>
</div>
<div class='col-md-4'>
<label class="labelav largeFile" for="file3">
<input type="file" id="file3" class="file img3" name="photo3">
<img id="photo3" src="#" alt="">
</label>
</div>
<div class='col-md-4'>
<label class="labelav largeFile" for="file4">
<input type="file" id="file4" class="file img4" name="photo4">
<img id="photo4" src="#" alt="">
</label>
</div>
</form>