Created
May 20, 2014 17:35
-
-
Save jerryvig/1016227bf84f94f2c688 to your computer and use it in GitHub Desktop.
HTML5 Drag & Drop Basic Example
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
//Suppose that you have a draggable span like this. | |
// <span style="position:relative;top:3px;" ng-bind="entity.Entity.Name" draggable="true" data-type="result"></span> | |
//Then implement draggability like this. | |
var draggableSpanList = $('span[draggable="true"]').get(); | |
$.each(draggableSpanList, function(idx, span) { | |
span.addEventListener('dragstart', function (evt) { | |
evt.stopPropagation(); | |
evt.dataTransfer.setData('text/plain', JSON.stringify({ | |
name: evt.target.innerHTML.trim(), | |
type: evt.target.getAttribute('data-type') | |
})); | |
}, false); | |
span.addEventListener('dragend', function (evt) { | |
evt.stopPropagation(); | |
}, false); | |
}); | |
//Now suppose that you have a <div> that you want to drop onto like this. | |
// <div class="box collapse in" id="xaxis"> | |
// <div class="pivot-droparea"> | |
// </div> | |
//</div> | |
// Implement the droppable like this. You need to evt.stopPropagation() and evt.preventDefault() on a few of these events. | |
//X-Axis Drop Area | |
var xAxisDropArea = $('#xaxis').find('.pivot-droparea').get(0); | |
xAxisDropArea.addEventListener('dragenter', function (evt) { | |
evt.stopPropagation(); | |
$(xAxisDropArea).addClass('over'); | |
}, false); | |
xAxisDropArea.addEventListener('dragover', function (evt) { | |
evt.stopPropagation(); | |
evt.preventDefault(); | |
return false; | |
}, false); | |
xAxisDropArea.addEventListener('dragleave', function (evt) { | |
evt.stopPropagation(); | |
$(xAxisDropArea).removeClass('over'); | |
}, false); | |
xAxisDropArea.addEventListener('drop', function (evt) { | |
evt.stopPropagation(); | |
evt.preventDefault(); | |
var obj = JSON.parse(evt.dataTransfer.getData('text/plain')); | |
if (obj.type === 'result') { | |
if (xAxisResults.indexOf(obj.name) === -1) { | |
$(xAxisDropArea).append('<div>' + obj.name.trim() + '</div>'); | |
xAxisResults.push(obj.name); | |
} | |
} else if (obj.type === 'setting') { | |
if (xAxisSettings.indexOf(obj.name) === -1) { | |
$(xAxisDropArea).append('<div>' + obj.name.trim() + '</div>'); | |
xAxisSettings.push(obj.name); | |
} | |
} | |
$(xAxisDropArea).removeClass('over'); | |
return false; | |
}, false); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment