1

I want to create a rectangle on mousedown that drags across a grid and remains there on mouseup, snapping to the gridlines and outputting the coordinates for top left and bottom right of the it's position (x1,x2,y1,y2). Any help on starting to build this would be much appreciated.

I have a 500x500 grid with squares of 10x10 (example - jsFiddle).

Grid Code:

      function creategrid(size){

          var standardW = Math.floor((500) / size),
              standardH = Math.floor((500) / size);

          var standard = document.createElement('div');
              standard.className = 'grid';
              standard.style.width = (standardW * size) + 'px';
              standard.style.height = (standardH * size) + 'px';

            for (var i = 0; i < standardH; i++) {
                for (var p = 0; p < standardW; p++) {
                  var cell = document.createElement('div');
                      cell.style.height = (size - 1) + 'px';
                      cell.style.width = (size - 1) + 'px';
                      cell.style.position = 'relative'
                      cell.style.zIndex= '2';
            standard.appendChild(cell);
                }
            }

          document.body.appendChild(standard);
      }

      creategrid(10);

CSS for grid:

  .grid {
    margin: 0px auto auto;
    border: 1px solid #000;
    border-width: 0 1px 1px 0;
    background-color: #CCC;
  }

  .grid div {
    border: 1px solid #000;
    border-width: 1px 0 0 1px;
    float: left;
  }

  #tooltip { 
    text-align:center; 
    background:black; 
    color:white; 
    padding:3px 0; 
    width:150px; 
    position:fixed; 
    display:none; 
    white-space:nowrap;
    z-index:3; 
  }

I've found some snapping code through google http://jqueryui.com/draggable/#snap-to but I am literally stuck (I'm a complete beginner at JQuery).

Alternatively if anyone has a better idea of how to do this then that would be more than welcome.

  • Some background if you want to suggest a different way to do it: This is for a website running off of an SQL server built in python and django. The data it outputs are jSON objects but otherwise I'm just using html, css and javacript/jQuery for the front end. -- Not sure if that info is useful or not.

EDIT added code for mouseover grid coordinates in jQuery

    $(window).load(function() {
        var tooltip = $('<div id="tooltip">').appendTo('body')[0];

        $('.coords').
        each(function() {

            var pos = $(this).offset(),
                top = pos.top,
                left = pos.left,
                width = $(this).width(),
                height = $(this).height();

            $(this).
            mousemove(function(e) {
                var x = ((e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft) - left).toFixed(0),
                    y = (((e.clientY + document.body.scrollTop + document.documentElement.scrollTop) - top)).toFixed(0);

                    $(tooltip).text( x + ', ' + y).css({
                        left: e.clientX + 20,
                        top: e.clientY + 10
                    }).show();

            }).

            mouseleave(function() {
                $(tooltip).hide();
            });

        });

    });
Cameron Guthrie
  • 141
  • 1
  • 9

2 Answers2

5

If i understood your question correctly, you don't really need jQueryUI for that. You need to find mouse position snapped to the cell of the grid on mousemove and resize your selection rectangle.

function getMousePos (e) {
  return {
    'left': Math.floor((e.pageX - gridOffset.left) / cellSpacing) * cellSpacing,
    'top': Math.floor((e.pageY - gridOffset.top) / cellSpacing) * cellSpacing
  }
}

Here is an example - http://jsfiddle.net/4efTV/

dimusic
  • 4,123
  • 2
  • 28
  • 31
  • This works perfectly! Thank you. Do you know happen if there is a way to make it so the selection box could be drawn in directions other than down and to the right? – Cameron Guthrie Jan 30 '13 at 01:47
2

I recommend you to use that plugin, jQuery UI, its really simple to use take a look at this fiddle: http://jsfiddle.net/promatik/hBQxb/

HTML

<div class="snap-box">snap box</div>

Javascript:

$( ".snap-box" ).draggable({ grid: [ 10,10 ] });

CSS:

.snap-box {
    width: 50px;
    height: 50px;
    position: absolute;
    z-index: 10;
}
António Almeida
  • 9,620
  • 8
  • 59
  • 66
  • That's almost what I was after but maybe I wasn't quite clear enough, I'm going to have a read through of the api for jQuery UI now though so thanks :) Just to clarify I basically want to be able to draw a selection box from where the mouseDown is on the grid (snapping to the nearest 10x10) to where the mouseUp is on the grid (snapping again)... and then spittting out coordinates. – Cameron Guthrie Jan 29 '13 at 02:38
  • By the way, to use this in your application, you'll have to import jQuery library and jQuery UI (http://jqueryui.com/download/) – António Almeida Jan 29 '13 at 02:39