Retrieve coordinates when click on image

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 <div> 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!

Advertisements

About admin

Just another php developer trying to give something back to the community.
This entry was posted in Javascript, Script and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s