Skip to content

Instantly share code, notes, and snippets.

@turtlix
Created November 26, 2013 06:06
Show Gist options
  • Save turtlix/7654089 to your computer and use it in GitHub Desktop.
Save turtlix/7654089 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
body { font-family: sans-serif; }
#container {
width: 400px;
height: 300px;
background: #ddd;
line-height: 300px;
text-align: center;
color: #666;
-moz-user-select: none;
-webkit-user-select: none;
user-select: none;
}
.selection-box {
position: absolute;
background: transparent;
border: 1px dotted #000;
}
</style>
</head>
<body>
<div id="container">Draw selection here</div>
<p id="mousedown"></p>
<p id="mouseup"></p>
</body>
</html>
$(function() {
var $container = $('#container');
var $selection = $('<div>').addClass('selection-box');
var $mouseDown = $('#mousedown');
var $mouseUp = $('#mouseup');
$container.on('mousedown', function(e) {
var click_y = e.pageY, click_x = e.pageX;
var $div = $(e.target);
var offset = $div.offset();
var x = e.clientX - offset.left;
var y = e.clientY - offset.top;
$mouseDown.text('Down: ' + x + ',' + y);
$selection.css({
'top': click_y,
'left': click_x,
'width': 0,
'height': 0
});
$selection.appendTo($container);
$container.on('mousemove', function(e) {
var move_x = e.pageX,
move_y = e.pageY,
width = Math.abs(move_x - click_x),
height = Math.abs(move_y - click_y),
new_x, new_y;
new_x = (move_x < click_x) ? (click_x - width) : click_x;
new_y = (move_y < click_y) ? (click_y - height) : click_y;
$selection.css({
'width': width,
'height': height,
'top': new_y,
'left': new_x
});
}).on('mouseup', function(e) {
$container.off('mousemove');
$selection.remove();
var $div = $(e.target);
var offset = $div.offset();
var x = e.clientX - offset.left;
var y = e.clientY - offset.top;
$mouseUp.text('Up: ' + x + ',' + y);
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment