Skip to content

Instantly share code, notes, and snippets.

@demonio

demonio/dropimage.css

Last active Nov 24, 2020
Embed
What would you like to do?
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