Skip to content

Instantly share code, notes, and snippets.

@seejohnrun
Created May 15, 2013 04:37
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 seejohnrun/5581670 to your computer and use it in GitHub Desktop.
Save seejohnrun/5581670 to your computer and use it in GitHub Desktop.
Move around a fixed panel
(function($){
/*
* This is a jQuery extension to make it so that when you drag
* a fixed-position div's handle, you can resize the div.
*
* options.handleSelector (default='.handle') - how to find the handle
* options.direction (default='up') - the expansion direction
* options.min (default=0) - the min height (or width)
* options.max (default=clientHeight) - the max height (or width)
* options.moved (default=undefined) - called when size changes
*/
$.fn.toolbar = function (options) {
// Configurations
var configurations = {
'up': { vector: 'height', multiple: -1 },
'down': { vector: 'height', multiple: 1 },
'left': { vector: 'width', multiple: -1 },
'right': { vector: 'width', multiple: 1 }
};
// Take in the options, get what we need
options = options || {};
var $container = $(this),
$handle = $(this).find(options.handleSelector || '.handle');
// Select a configuration
var configuration = configurations[options.direction || 'up'];
if (!configuration) {
throw('Invalid direction. (' + options.direction + ')');
}
// Figure out what vector we're moving in
var pageAttribute = configuration.vector === 'width' ? 'pageX' : 'pageY';
// Track the original size so that we can animate back to it on dblclick
var defaultValue = $container[configuration.vector]();
// Bounds
var min = options.min || 0;
var max = options.max || $(window)[configuration.vector]();
// Track movement with this method
var trackMoved = function () {
if (options.moved) {
options.moved($container);
}
};
// Double click
$handle.on('dblclick', function () {
// Move back to the starting position
var css = {};
css[configuration.vector] = defaultValue.toString() + 'px';
$container.animate(css, trackMoved);
});
// Track when the handle is grabbed
$handle.on('mousedown', function (downEvent) {
// Prevent highlighting text while dragging
downEvent.preventDefault();
// Track where we start so we know what height to go to
var start = $container[configuration.vector](),
pos = downEvent[pageAttribute];
// When we let go, let go
$(document).on('mouseup', function () {
$(document).off('mouseup').off('mousemove');
});
// When we move, resize
$(document).on('mousemove', function (moveEvent) {
// Calculate the new height
var move = moveEvent[pageAttribute] - pos,
newValue = start + configuration.multiple * move;
// If we should change the height
if (newValue > min && newValue < max) {
$container[configuration.vector](newValue);
trackMoved();
}
});
});
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment