Jump to content

[SOLVED] get click coordinates problem in firefox


Dragen

Recommended Posts

Hi,

I've been searching for a while and can't figure out a solution.

I've got a script which gets the x and y coordinates when you click on an image, so I can tell where the user has clicked.

 

This works in ie, but when I run it in firefox it throws up a weird result.

If I click on it without scrolling down the page first, it will work fine, but if I scroll down the page slightly, then it gives false y coordinates.

I guess it's some confusion with the top of the page moving or something. If anyone can suggest a workaround I'd be very gratefull!

Here's my code (practically copied from here):

function getImgX(evt) {
var img_x;
var img_y;
if (document.all) { // MSIE
	img_x = evt.offsetX;
	img_y = evt.offsetY;
} else { // Netscape, etc.
	img_x = evt.clientX;
	img_y = evt.clientY;
	for (var offMark = evt.target; offMark; offMark = offMark.offsetParent) {
		img_x -= offMark.offsetLeft;
	}
	for (var offMark = evt.target; offMark; offMark = offMark.offsetParent) {
		img_y -= offMark.offsetTop;
	}
}

var coordinates = 'x: ' + img_x + ', y: ' + img_y;
alert (coordinates);
}

ah, another post I've solved ;)

 

I fixed it by first getting the position of the image on the page, which i was already doing, but i've changed the check into a seperate function so I can use it again.

 

Then I check if the page has been scrolled down and return the x and y coordinates of the scroll and add it to the current coordinates:

function getImgX(evt, obj) { //this is the main function
var img_x;
var img_y;
var c;
if (document.all) { // MSIE
	img_x = evt.offsetX;
	img_y = evt.offsetY;
} else { // Netscape, etc.
	img_x = evt.clientX;
	img_y = evt.clientY;

	c = findPos(obj); // here I get the images position
	img_x -= c[0];
	img_y -= c[1];

	c = checkscroll(); // then I check the scrollbar
	img_x += c[0];
	img_y += c[1];
}

var coordinates = 'x: ' + img_x + ', y: ' + img_y;
alert (coordinates);
}

function findPos(obj) {
var curleft = curtop = 0;
if (obj.offsetParent) {
	curleft = obj.offsetLeft
	curtop = obj.offsetTop
	while (obj = obj.offsetParent) {
		curleft += obj.offsetLeft
		curtop += obj.offsetTop
	}
}
return [curleft,curtop];
}

function checkscroll(){
var x;
var y;
if(window.pageXOffset){
	x = window.pageXOffset;
}else if(document.body.scrollLeft){
	x = document.body.scrollLeft;
}
if(window.pageYOffset){
	y = window.pageYOffset;
}else if(document.body.scrollTop){
	y = document.body.scrollTop;
}

if(x == undefined){
	x = 0;
}
if(y == undefined){
	y = 0;
}
return [x,y];
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.