when function with drag and drop list
when funciton this is a function that simply checks to make sure the event's target is what it is supposed to look for
the drag and drop list is less simple but it works well
by Darby Rathbone
June 24, 2014
HTML
<ul>
<li class='drag'><span>this is 1</span></li>
<li class='drag'><span>this is 2</span></li>
<li class='drag'><span>this is 3</span></li>
<li class='drag'><span>this is 4</span></li>
</ul>
CSS
.drag {
cursor:move;
text-align: center;
width:auto;
height:auto;
border:ridge 3px #cccccc;
overflow: hidden;
display:flex;
padding:10px;
margin:5px;
}
ul {
outline:inset 3px;
overflow:hidden;
width:auto;
}
JavaScript
var when = function (event, conditioncallback, truecallback, checkparents, falsecallback) {
this.addEventListener(event, function (e) {
var p = [];
p.push(e.target);
if(checkparents) {
while(p[p.length - 1].parentElement) {
p.push(p[p.length - 1].parentElement)
}
}
if((!(p.some(function (f) {
if(conditioncallback.call(f)) {
truecallback.bind(f, e).call();
return true
} else {
return false
}
}))) && falsecallback) {
falsecallback()
}
})
};
var dragging, offset;
var dragables = document.getElementsByClassName('drag');
[].slice.call(dragables).reverse().forEach(function (e) {
var b = getComputedStyle(e);
console.log(b);
e.style.top = b.top;
e.style.left = b.left
});
var pm = [0, 0];
when('mousedown',
function () { event.preventDefault(); return this.classList.contains('drag')},
function (e) {
var order = [].slice.call(dragables).sort(function (a, b) {
return parseInt(getComputedStyle(b)['z-index']) - parseInt(getComputedStyle(a)['z-index'])
});
order.unshift(this);
order = order.reverse();
order.forEach(function (a, i) {
if(!a.style) a.style;
a.style['z-index'] = i
});
this.style.position = 'relative';
dragging = this;
var b = getComputedStyle(this);
pm = [e.pageX, e.pageY];
offset = [e.pageX - (parseInt(b.left) || 0), e.pageY - (parseInt(b.top) || 0)];
e.preventDefault()
}, true);
when('mousemove',
function () { return dragging},
function (e) {
var dy = e.pageY - pm[1];
var before = dragging.getBoundingClientRect();
var ev = [e.pageX, e.pageY];
if(dy > 0) {
ev[1] = (before.bottom + 1)
}
if(dy < -0) {
ev[1] = (before.top - 1)
}
var ex = document.elementFromPoint(ev[0], ev[1]);
if(ex && dragging !== ex) {
if(dragging.parentElement === ex.parentElement) {
ex.parentElement.insertBefore(dragging, ex);
if(dy > 0) {
ex.parentElement.insertBefore(ex,...