dragfire
dragfire

Reputation: 433

Getting currently clicked co-ordinates relative to an element

i have a function to get the co-ordinates of the recently clicked position with respect to a div element without using JQuery which is working fine .

without jquery (working) :

var Board = document.getElementById("board"); // div element

function mouseListener(e)
{
    var posX = e.clientX - Board.getBoundingClientRect().left,
        posY = e.clientY - Board.getBoundingClientRect().top
    console.log(posX+" : "+posY);
}

window.addEventListener("mousedown", mouseListener,false);

But this one uses JQuery and giving different co-ordinates as compared to the previous code

using jquery(not working) :

var Board = $("#board");

function mouseListener(e)
{
   var posX = e.clientX - Number(Board.css("left").replace("px", "")),
       posY = e.clientY - Number(Board.css("top").replace("px", ""));
   console.log(posX+" : "+posY);
}

$(window).mousedown(mouseListener);

How to write this properly on jQuery so that it'll work like the first code?

Upvotes: 1

Views: 73

Answers (2)

Martin Ernst
Martin Ernst

Reputation: 3279

With jQuery you have to use .offset() to get the same values as with .getBoundingClientRect():

function mouseListener(e) {
   var posX = e.clientX - parseFloat(Board.offset().left),
       posY = e.clientY - parseFloat(Board.offset().top);
   console.log(posX+" : "+posY);
}

jQuery.fn.offset() Reference here;

There are three ways to attach the event-handler. Used in jQuery < 1.7 but still working in newer versions:

$(window).bind('mousedown', mouseListener);

As of jQuery 1.7 method .on() is used, it has the greatest flexibility also for event delegation:

$(window).on('mousedown', mouseListener);

The third is what you have used, it's only a shortcut and calls internally .on().

Reference jQuery.fn.bind() - - - - Reference jQuery.fn.on()

Upvotes: 2

M J
M J

Reputation: 81

Whatever you have done is absolutely correct logicwise, just minor syntactical mistakes.

var Board = $("#board");

function mouseListener(e)
{
    var posX = e.clientX - Number(Board.css("left").replace("px", "")),     //you forgot to put closing braces here and in the next line.
    posY = e.clientY - Number(Board.css("top").replace("px", ""));
    console.log(posX+" : "+posY);
}

$(window).mousedown(mouseListener);

Make sure you have used style left and top in the element with id "#board" else output will be NaN : NaN.

Upvotes: 0

Related Questions