Last active
October 27, 2016 22:56
-
-
Save rabidaudio/03005ddc64cc99f84955 to your computer and use it in GitHub Desktop.
A little jQuery plugin for draggable selections, a la whenisgood.net
This file contains hidden or 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
/** | |
* A simple little jQuery plugin for doing draggable selections (like http://whenisgood.net/). | |
* Maybe not super performant, but it's jQuery so you already don't care. | |
* | |
* Demo: | |
* http://jsfiddle.net/qa06oab2/ | |
* | |
* Usage: | |
* $(<selector for elements>).dragHighlight(<optional name of class to add, defaults to 'selected'>); | |
* | |
* Author: | |
* Charles Julian Knight, [email protected] | |
* | |
* License: | |
* MIT | |
*/ | |
(function ($) { | |
//http://stackoverflow.com/a/2700029 | |
var disableSelection = function () { | |
return this.attr('unselectable', 'on') | |
.css('user-select', 'none') | |
.on('selectstart', false); | |
}; | |
var enableSelection = function () { | |
return this.attr('unselectable', 'off') | |
.css('user-select', 'inherit') | |
.off('selectstart'); | |
}; | |
var state = 'none'; | |
function selectOrDeselect() { | |
if (state === 'select') { | |
$(this).addClass('selected'); | |
} else if (state == 'deselect') { | |
$(this).removeClass('selected'); | |
} | |
} | |
$.fn.dragHighlight = function (className) { | |
var self = this; | |
className = className || 'selected'; | |
$(self).on('mouseover', selectOrDeselect).on('mousedown', function () { | |
//first element to get dragged | |
state = ($(this).hasClass(className) ? 'deselect' : 'select'); | |
disableSelection.bind(self).call(); | |
selectOrDeselect.bind(this).call(); | |
$(self).first().trigger('dragHighlightStart', this, state); | |
//start listening for the end | |
$(document).on('mouseup', function () { | |
state = 'none'; | |
enableSelection.bind(self).call(); | |
$(document).off('mouseup'); | |
$(self).first().trigger('dragHighlightEnd', state); | |
}); | |
}); | |
return self; | |
} | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment