Created
March 24, 2014 17:50
-
-
Save tanrax/9745424 to your computer and use it in GitHub Desktop.
JS: Drag and drop (arrastrar y soltar)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Drag and drop</title> | |
<style> | |
.ficha { | |
width: 100px; | |
height: 100px; | |
float: left; | |
background-color: red; | |
cursor: move; | |
} | |
.ficha.over { | |
border: 2px dashed #000; | |
} | |
</style> | |
</head> | |
<body> | |
<div class="ficha" draggable="true">1</div> | |
<div class="ficha" draggable="true">2</div> | |
<script> | |
/** Drag and drop **/ | |
var dragSrcEl = null; | |
var cols = document.querySelectorAll('.ficha'); | |
//guardamos el contenido que queremos cambiar para la transferencia al dejar de arrastrar | |
function handleDragStart(e) { | |
dragSrcEl = this; | |
e.dataTransfer.effectAllowed = 'move'; | |
e.dataTransfer.setData('text/html', this.innerHTML); | |
} | |
function handleDragOver(e) { | |
if (e.preventDefault) { | |
e.preventDefault(); | |
} | |
e.dataTransfer.dropEffect = 'move'; //efecto al mover | |
return false; | |
} | |
function handleDragEnter(e) { | |
this.classList.add('over');//agregamos borde rojo en el estilo css | |
} | |
function handleDragLeave(e) { | |
this.classList.remove('over'); //eliminamos borde rojo en el estilo css | |
} | |
function handleDrop(e) { | |
if (e.stopPropagation) { | |
e.stopPropagation(); //evitamos abrir contenido en otra pagina al soltar | |
} | |
//hacemos el intercambio de contenido html de el elemento origne y destino | |
if (dragSrcEl != this) { | |
dragSrcEl.innerHTML = this.innerHTML; | |
this.innerHTML = e.dataTransfer.getData('text/html'); | |
this.classList.remove('over'); | |
} | |
return false; | |
} | |
function handleDragEnd(e) { | |
[].forEach.call(cols, function (col) { | |
col.classList.remove('over');//eliminamos el borde rojo de todas las columnas | |
}); | |
} | |
//agregamos todos los eventos anteriores a cada columna mediante un ciclo | |
[].forEach.call(cols, function(col) { | |
col.addEventListener('dragstart', handleDragStart, false); | |
col.addEventListener('dragenter', handleDragEnter, false); | |
col.addEventListener('dragover', handleDragOver, false); | |
col.addEventListener('dragleave', handleDragLeave, false); | |
col.addEventListener('drop', handleDrop, false); | |
col.addEventListener('dragend', handleDragEnd, false); | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment