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

4
  • ok, what's the question? Commented Nov 30, 2015 at 16:39
  • I want to replace the background of my div by the uploaded file. Commented Nov 30, 2015 at 16:39
  • ok, what have you tried? We are happy to help but can't really do it for you Commented Nov 30, 2015 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? Commented Nov 30, 2015 at 16:45

1 Answer 1

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/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.