Computing Magazine

Retrieve Coordinates When Click on Image

Posted on the 10 July 2014 by Akahgy

Description:

HTML forms allow the use of an image as a submit button, and the action triggers the send of the x and y coordinates of the click relative to the image size. However, why not take it to the next level, and record on the go the image click coordinates?

Solution:

1. Create a

containing the image, with an id and an action name for the onmousedown event:

<div id=”image_wrapper” onmousedown=”recordClick(event)”>

2. Create a wrapper for the results(div, table, whatever you want):

<div id=”coordinatesOutput”>Coordinates will be here</div>

3. Add the magic javascript:

var coordinatesArray = [];
var i= 0;

function recordClick(event) {
i++;
coordinates[i] = x_pointer+’,’+y_pointer;
printCoordinates();
document.getElementById(“image_wrapper”).style.cursor = ‘crosshair’;
}

function printCoordinates(){
var coordinates = “”;
for(var j=1;j<coordinatesArray .length;j++){
coordinates += coordinatcoordinatesArray[j]+’<br />;
}

document.getElementById(‘coordinatesOutput’).innerHTML = coordinates;
}

4. Just put it altogether with some styling in a nice HTML block, and enjoy!


Back to Featured Articles on Logo Paperblog

Magazine