Dragen Posted November 21, 2007 Share Posted November 21, 2007 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); } Quote Link to comment Share on other sites More sharing options...
Dragen Posted November 21, 2007 Author Share Posted November 21, 2007 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]; } Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.