Curnelious
Curnelious

Reputation: 1

Set an image div as an input to upload an image

I would like to get the effect of a square image that when you click it you will be able to select another image from your files to replace that image.

So I have this image div:

<div class="uploader boxCorners">
   <div class="imagePreview"> <img src="http://i.pravatar.cc/500?img=7"/></div>
</div>

And when clicking the imagePreview I need to be able to upload another image.

I know you upload a file with:

<input type='file' id="imageUpload" accept=".png, .jpg, .jpeg" />

How to set the image to be the input (without getting that ugly upload button) and replace it with the new one?

Upvotes: 0

Views: 173

Answers (1)

Andy Hoffman
Andy Hoffman

Reputation: 19111

You could try something like this:

  • Create relative container
  • Stretch absolutely positioned file input to the corners of the parent container
  • Set pointer-events: none on the image, so the click reaches the input

.imagePreview {
  position: relative;
}

.imagePreview img {
  pointer-events: none;
}

[type="file"] {
  cursor: pointer; /* <-- Let people know it's clickable */
  opacity: 0;
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}
<div class="uploader boxCorners">
  <div class="imagePreview"> 
    <img alt="Super cute cat" src="http://placekitten.com/200/200" />
    <input type="file">
  </div>
</div>

jsFiddle

Upvotes: 1

Related Questions