Skip to content

Instantly share code, notes, and snippets.

@jennschiffer
Last active December 11, 2015 14:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jennschiffer/4618041 to your computer and use it in GitHub Desktop.
Save jennschiffer/4618041 to your computer and use it in GitHub Desktop.
Draggy Divs (jQuery)
.draggy { padding: 10px; position: absolute; top: 20px; left: 20px; }
.dragger { margin: 0; position: absolute; top: 5px; right: 5px; cursor: pointer; font-size: 1.5em; }
$(document).ready(function(){
// add dragger icon to upper-right corner of draggy box
$('.draggy').prepend('<p class="dragger">[&harr;]</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