Handler for a control to pan a map in four directions I have a pan control that look like this:



Pretty standard Google Mapsish controls, IMO.

When the user clicks in the top 3rd of the control, it should pan up (deltaY = +1); right third means it should pan east (deltaX = -1); Down is deltaY = -1, and West is deltaX = +1. The control is 50px, square. I have working code, but I believe it can be written much more elegantly than this using a single (if discontinuous) mathematical function.

$(control).click(function (evt) {
    var clickPointX = (evt.layerX || evt.offsetX),
        clickPointY = (evt.layerY || evt.offsetY),
        deltaX,
        deltaY;

    // control is 50x50 px.
    // Click in the top third, get a positive 'Y' value.
    // Click in the left third, get a positive 'X' value.
    // Click in the middle, get zero.
    if (clickPointX &lt; 16) {
        deltaX = +1;
    } else if (clickPointX &gt; 34) {
        deltaX = -1;
    } else {
        deltaX = 0;
    }

    if (clickPointY &lt; 16) {
        deltaY = +1;
    } else if (clickPointY &gt; 34) {
        deltaY = -1;
    } else {
        deltaY = 0;
    }
    map.panDirection(deltaX, deltaY);
});
A few improvements:


replace magic numbers
extract repetition into a function
dynamically calculate dimensions


Example code:



function getDelta(clickPoint, controlDimension, threshold){
    var delta;
    if (clickPoint &lt; threshold) {
        delta = +1;
    } else if (clickPoint &gt; controlDimension- threshold) {
        delta = -1;
    } else {
        delta = 0;
    }
    return delta;
}

$(document).ready(function () {
    var control = $('#example');
    var controlHeight = control.height();
    var controlWidth = control.width();
    var widthThreshold = controlHeight/3;
    var heightThreshold = controlWidth/3;
    
    $(control).click(function (evt) {
        var clickPointX = (evt.layerX || evt.offsetX);
        var clickPointY = (evt.layerY || evt.offsetY);
        var deltaX = getDelta(clickPointX, controlWidth, widthThreshold);
        var deltaY = getDelta(clickPointY, controlHeight, heightThreshold);
        alert('delta x: ' + deltaX + '\n' + 'delta y: ' + deltaY);
        //map.panDirection(deltaX, deltaY);
    });
});
&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"&gt;&lt;/script&gt;
&lt;html&gt;
    &lt;div id='example' style='background-color: red; height: 50px; width: 50px;' /&gt;
&lt;/html&gt;