Last active
December 11, 2015 14:59
-
-
Save jennschiffer/4618041 to your computer and use it in GitHub Desktop.
Draggy Divs (jQuery)
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
.draggy { padding: 10px; position: absolute; top: 20px; left: 20px; } | |
.dragger { margin: 0; position: absolute; top: 5px; right: 5px; cursor: pointer; font-size: 1.5em; } |
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
$(document).ready(function(){ | |
// add dragger icon to upper-right corner of draggy box | |
$('.draggy').prepend('<p class="dragger">[↔]</p>'); | |
// start dragging when the icon is clicked | |
$('.dragger').mousedown(function() { | |
var box = $(this).parent('.draggy'); | |
box.addClass('dragging'); | |
$('#test').html('dragging'); | |
if ( window.getSelection) { | |
window.getSelection().removeAllRanges(); | |
} | |
else if (document.selection) { | |
document.selection.clear(); | |
} | |
resetSelectStart = document.onselectstart; | |
document.onselectstart = function() { return false; }; | |
}); | |
// stop dragging when the icon is no longer clicked | |
$(window).mouseup(function() { | |
$('.draggy').removeClass('dragging'); | |
$('#test').html('not dragging'); | |
document.onselectstart = resetSelectStart; | |
}); | |
// move the dragging box wherever the cursor goes | |
$(window).mousemove(function(event) { | |
$('.dragging').each(function() { | |
var box = $(this); | |
if ( !box.hasClass('dragging') ) { | |
// nothing to be dragged herrre, Nelly | |
} | |
else { | |
box.css('top', event.pageY -15 ).css('left', event.pageX - box.width()); | |
} | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment