0

I want to replace the background of my div by the uploaded file. Note that this div is my Upload Button, and that its background changes on :hover and :active. When the file should be uploaded to the background, the :hover and :active attributes should not have effect.

HTML

<form>
<input id="uploader1" type="file" accept="image/*" style="display:none;" required>
<label for="uploader1">
     <div class="square" id="myImg1"></div>
</label>

CSS

.square{
    position: relative;
    width: 50%;
    cursor: pointer;
}
.square:before{
    padding-top: 95%;
    display:block;
    content: "";
}
#myImg1 {
 background: url('button.jpg') no-repeat center;
 background-size: cover;
}
#myImg1:hover {background:url('buttonHover.jpg') no-repeat center;
background-size: cover;
}
#myImg1:active {
background:url('buttonClick.jpg') no-repeat center;
background-size: cover;
}
#uploader1 > input {
display:none;
}

JSFIDDLE DEMO

St Klauz
  • 65
  • 1
  • 9
  • ok, what's the question? – StudioTime Nov 30 '15 at 16:39
  • I want to replace the background of my div by the uploaded file. – St Klauz Nov 30 '15 at 16:39
  • ok, what have you tried? We are happy to help but can't really do it for you – StudioTime Nov 30 '15 at 16:40
  • I've tried the #uploader1 > input, which would work if there was no :hover and :active attributes above it, but since there are, it always ended up being replaced by the hover... I've looked around everywhere, and i don't really know what to do anymore. I was thinking of also creating a toggle button, so if there was input, the toggle would be "on", and the css would change. but that's overthinking it.. Is there any way of doing this in a simpler way? Like, it knows that there is input, and it changes the css to put the input as a background and ignore the :hover and :active? – St Klauz Nov 30 '15 at 16:45

1 Answers1

1

I think I got it for you.

I did this:

$("#uploader1").change(function(){
    $("#myImg1").css("background-image", "url("+URL.createObjectURL($(this)[0].files[0])+")");
});

https://jsfiddle.net/8y98uds6/2/

Chris
  • 987
  • 6
  • 24