0 Members and 1 Guest are viewing this topic.
<html><head> <title>Selection field</title> <script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"></script> <script type="text/javascript"> var mouseX = 0, mouseY = 0, startX = 0, startY = 0, colliders = []; window.onmousedown = function() { //Defaults $('#selector') .css('position', 'absolute') .css('opacity', 0.50); //Declarations startX = mouseX; startY = mouseY; //Apply $('#selector').css('left', startX); $('#selector').css('top', startY); //Show $('#selector').show(); } window.onmousemove = function(e) { //Set mouse values mouseX = e.pageX; mouseY = e.pageY; //Positioning values var tX, tY, w, h; //Calculate X if ( (mouseX - startX) >= 0 ) { tX = startX; w = mouseX - startX; } else { tX = startX + ( mouseX - startX ); w = (mouseX - startX) * -1; } //Calculate Y if ( (mouseY - startY) >= 0 ) { tY = startY; h = mouseY - startY; } else { tY = startY + ( mouseY - startY ); h = (mouseY - startY) * -1; } //Apply $('#selector').css({ left: tX, top: tY, width: w, height: h }); //Check for collision //Private function to detect collision (called twice, once horizontal, once vertical) function cps(p1, p2) { var x1 = p1[0] < p2[0] ? p1 : p2; var x2 = p1[0] < p2[0] ? p2 : p1; return x1[1] > x2[0] || x1[0] === x2[0] ? true : false; } //Store the selector position data in this array var sel = [[tX, tX + w], [tY, tY + h]]; $.each(colliders, function(key, i) { var selectionBorder = ( cps(sel[0], this[1]) && cps(sel[1], this[2]) ) ? '1px solid black' : '1px solid white'; if ( $('#selector').css('display') == 'block' ) { $(this[0]).css('border', selectionBorder); } }); //Override return false; } window.onmouseup = function() { $('#selector').hide(); } //Init function init () { $('#selector').hide(); $('.selectable').each(function (key, i) { var pos = $(this).position(); colliders.push([this, [ pos.left, pos.left + $(this).innerWidth() ], [ pos.top, pos.top + $(this).innerHeight() ] ]); }); }; </script></head><body onload="javascript:init();"> <div class="selectable" style="position:absolute;left:500px;top:500px;width:100px;height:100px;background-color:red;border:1px solid white;"></div> <div class="selectable" style="position:absolute;left:800px;top:200px;width:100px;height:100px;background-color:blue;border:1px solid white;"></div> <div style="background:lightblue;border:1px solid blue;display:none:position:absolute;width:0px;height:0px;left:0px;top:0px;z-index:9001" id="selector"></div></body></html>
I like it! I actually needed a drag-to-select engine for my Phinder project.
Can you add like a button that, when pressed, sets all selected elements to display: none;? I would like to see how that would work. Also, I'm talking about the demo