Reputation: 506
On a webpage, I display a users profile picture which they have assigned. Below this, I have a file input which allows a user to select a new profile picture. I want to display the new profile picture where the current profile picture is on the webpage.
For this, I need to change the src of the <img>
tag that displays the users current profile picture. I need to change the src
attribute of the img
to whatever file the user selects when they want to change the profile picture.
I have put together some code, however it doesn't work at all.
Here is my HTML:
// Profile picture I display in browser <img style="position: relative; left: 60px; top: 25px;" width="55px" src="{{ user.profilePic.url }}" alt="">
<label id="profilePhoto_update" for="profilepic_update">Change Profile Photo</label>
JS:
img = $("#profilePhoto_update")
$("#profilePhoto_update").change(function(e) {
for (var i = 0; i < e.originalEvent.srcElement.files.length; i++) {
var file = e.originalEvent.srcElement.files[i];
var reader = new FileReader();
reader.onloadend = function() {
img.src = reader.result;
}
reader.readAsDataURL(file);
$("#profilePhoto_update").after(img);
}
});
Does anybody know how to implement this functionality? Thank you.
Upvotes: 0
Views: 333
Reputation: 1675
You're binding the event to the <label>
instead of the <input>
.
Also, I'd recommend using Object URLs instead of Data URLs.
Here's a fixed example:
img = $("#profilePhotoImg")
$("#profilePhotoInput").change(function(e) {
var url = URL.createObjectURL(e.target.files[0])
img.attr('src', url)
});
I hope this helps!
Upvotes: 1