dante
dante

Reputation: 141

Show image on input select file

I have done a input to change a profile image, but I would like that when I select a new file, my input changes automatically to the new picture.

<div class="form-group" align="center">
  <div style="position:relative; bottom:-90px; opacity:0.5; z-index:1; color:black;background:white;font-weight:bold">alterar</div>
  <label style="display: block" for="avatar">
    <img src="{{  $user->avatar }}" style="-moz-border-radius: 50px;border-radius: 50px;height: 80px" id="imgupload">
  </label>
  <div class="col-md-6">
    <input type="file" class="form-control" name="avatar" id="avatar" style="display: none">
  </div>
</div>

I am not sure how I can accomplish that.

EDIT

I accomplished adding JS, but when I select a new image it's changing the rounded border..

JS:

    function readFile() {
      if (this.files && this.files[0]) {
        var FR= new FileReader();
        FR.onload = function(e) {
          document.getElementById("imgupload").src = e.target.result;
        };
        FR.readAsDataURL( this.files[0] );
      }
    }

    document.getElementById("avatar").addEventListener("change", readFile, false);

https://jsfiddle.net/gst96zax/

Upvotes: 1

Views: 1189

Answers (1)

dante
dante

Reputation: 141

I added the following JS

    function readFile() {
      if (this.files && this.files[0]) {
        var FR= new FileReader();
        FR.onload = function(e) {
          document.getElementById("imgupload").src = e.target.result;
          document.getElementById("imgupload").style.width = "80px";

        };
        FR.readAsDataURL( this.files[0] );
      }
    }

    document.getElementById("avatar").addEventListener("change", readFile, false);

https://jsfiddle.net/gst96zax/1

Upvotes: 1

Related Questions