Last active
January 15, 2016 16:06
-
-
Save eschwartz/b72e10766c3b9990622c to your computer and use it in GitHub Desktop.
Drag and Drop
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
/* Prevent the text contents of draggable elements from being selectable. */ | |
[draggable] { | |
-moz-user-select: none; | |
-khtml-user-select: none; | |
-webkit-user-select: none; | |
user-select: none; | |
/* Required to make elements draggable in old WebKit */ | |
-khtml-user-drag: element; | |
-webkit-user-drag: element; | |
} | |
li { | |
padding: 10px; | |
outline: 1px dotted green; | |
} | |
.drag-target-above { | |
border-top: 2px solid red; | |
} | |
.drag-target-below { | |
border-bottom: 2px solid red; | |
} |
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
<ul> | |
<li draggable="true" id="1">Item A</li> | |
<li draggable="true" id="2">Item B</li> | |
<li draggable="true" id="3">Item C</li> | |
</ul> |
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
const items = document.getElementsByTagName('li'); | |
$.event.props.push('dataTransfer'); | |
$('li') | |
.on('dragstart', evt => { | |
evt.target.style.opacity = '0.4'; | |
evt.dataTransfer.setData('text/plain', evt.target.id); | |
}) | |
.on('dragend', evt => { | |
$(evt.target).css({ | |
opacity: 1 | |
}); | |
$('li').css({ | |
borderTop: 'none', | |
borderBottom: 'none' | |
}) | |
}) | |
.on('dragover', evt => { | |
const isAboveTarget = isEventAboveTarget(evt); | |
$(evt.target).css({ | |
borderTop: isAboveTarget ? '2px solid green' : 'none', | |
borderBottom: isAboveTarget ? 'none' : '2px solid green' | |
}); | |
}) | |
.on('dragleave', evt => { | |
$(evt.target).css({ | |
borderTop: 'none', | |
borderBottom: 'none' | |
}); | |
}) | |
.on('dragover', evt => evt.preventDefault() ) // necessary for some reason | |
.on('drop', evt => { | |
evt.stopPropagation(); | |
const $sourceEl = $('#' + evt.dataTransfer.getData('text/plain')); | |
if (isEventAboveTarget(evt)) { | |
$sourceEl.insertBefore(evt.target); | |
} | |
else { | |
$sourceEl.insertAfter(evt.target); | |
} | |
evt.dataTransfer.clearData(); | |
}); | |
function isEventAboveTarget(mouseEvt) { | |
return mouseEvt.offsetY < $(mouseEvt.target).outerHeight() / 2; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment