I need to give a area on the page where anywhere in that area the user can click. When the user clicks, I want to import where they clicked on the page into a javascript variable. For example, if they clicked in the center of the page I want the javascript variable to be "50% 50%" If they clicked on the left corner of the page it would be "0% 0%" and so on. How would I do this? And Please only Javascript and html and css. No JQuery
Asked
Active
Viewed 74 times
0
-
You need to search for words "javascript click coordinates". Have a look at this question http://stackoverflow.com/questions/23744605/javascript-get-x-and-y-coordinates-on-mouse-click – jfrej Aug 12 '15 at 15:03
1 Answers
2
This code should be a good enough place for you to start...
See it in action at: http://jsfiddle.net/22rx6wp5/
var clickArea = document.getElementById ('click-area');
var percents = document.getElementById ('percents');
var clickRect = clickArea.getBoundingClientRect ();
var x, y, xp, yp, percentages;
// Click function
clickArea.onclick = function (event) {
var cx, cy;
// Get click position
if (navigator.appVersion.indexOf('MSIE') != -1) {
cx = event.clientX;
cy = event.clientY;
} else {
cx = event.pageX;
cy = event.pageY;
}
// Relate position to element position on page
x = cx - this.offsetLeft;
y = cy - this.offsetTop;
// Calculate position in percentage
xp = Math.round ((x / clickRect.width) * 100);
yp = Math.round ((y / clickRect.height) * 100);
// Percentages text
percentages = xp + '% ' + yp + '%';
// Display percentages in percents span
percents.textContent = percentages;
// Display percentages in browser console
console.log (percentages);
};

Coffee'd Up Hacker
- 1,356
- 11
- 23