Make image preview by changing the background-image of the div

Asked

Viewed 73 times

-1

I am willing to allow the client to change the cover photo of his social network, but I need to make a preview for it.

I can’t put an img tag on it right now 'cause it’s gonna mess up the whole design.

I would like to set the image through the Background-Image property of the DIV parent cover.

Follow the code of how I’m trying to do:

$(function(){
        $('#mudarcapa').change(function(){
            const file = $(this)[0].files[0]
            const fileReader = new FileReader()
            fileReader.onloadend = function(){
                $('#capa').css("background-image", fileReader.result); 
            }
            fileReader.readAsDataURL(file);
        })
    })
<label for="mudarcapa" class="mudarcapa">
    <a>Adicionar Capa</a>
</label>
<input type="file" name="arquivo" id="mudarcapa">

1 answer

0

function readURL(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();
    
    reader.onload = function(e) {
     $('#capa').css('background-image', 'url(' + e.target.result + ')');
    }
    
    reader.readAsDataURL(input.files[0]);
  }
}

$("#imgInp").change(function() {
  readURL(this);
});
#capa {
width:50px;
height:50px;
background-position:center;
background-size:contain;
border:1px solid red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form runat="server">
  <input type='file' id="imgInp" />
</form>

<div id="capa"></div>

Credits to https://stackoverflow.com/questions/4459379/preview-an-image-before-it-is-uploaded by the organised code; where only the src by attribute background-image

Browser other questions tagged

You are not signed in. Login or sign up in order to post.