Skip to content

Instantly share code, notes, and snippets.

@demonio
Last active November 24, 2020 13:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save demonio/29168132166ebdae82178e24757c0831 to your computer and use it in GitHub Desktop.
Save demonio/29168132166ebdae82178e24757c0831 to your computer and use it in GitHub Desktop.
Arrastra una imagen al label con el input[type="file"] y el js hará una cargar previa... :P
.dropimage {
position: relative;
border: 4px dashed grey;
min-height: 150px;
}
.dropimage:after {
color: grey;
content: "Drop image";
font-size: 30px;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
z-index: 1;
}
.dropimage input {
left: 0;
width: 100%;
height: 100%;
border: 0;
margin: 0;
padding: 0;
opacity: 0;
cursor: pointer;
position: absolute;
z-index: 2;
}
.dropimage img {
width: 100%;
}
$('body').on('change', '[type="file"]', function(eve) {
var img = $(this).parent().find('img'),
label = $(this).parent(),
reader = new FileReader();
console.log([img, eve, label, reader]);
reader.onloadend = function() {
if (img.length) {
$(img).attr('src', reader.result);
} else {
$(label).css('background-image', 'url(' + reader.result + ')');
$(label).css('background-repeat', 'no-repeat');
$(label).css('background-size', 'cover');
}
}
reader.readAsDataURL(eve.target.files[0]);
});
document.addEventListener("DOMContentLoaded", function() {
[].forEach.call(document.querySelectorAll('.dropimage'), function(label) {
label.onchange = function(e) {
var inputfile = this,
reader = new FileReader();
reader.onloadend = function() {
var img = inputfile.children[1];
if (img !== undefined) {
img.src = reader.result;
} else {
inputfile.style['background-image'] = 'url(' + reader.result + ')';
inputfile.style['background-repeat'] = 'no-repeat';
inputfile.style['background-size'] = 'cover';
}
}
reader.readAsDataURL(e.target.files[0]);
}
});
});
<label class="dropimage">
<input type="file" name="imagenes[]">
<?php if ($partida->fotos): ?>
<img alt="..." src="...">
<?php endif; ?>
</label>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment