0

I am trying to replicate something like a volume slider or video seekbar where, when the user clicks a point, the indicator jumps to that location.

To do that, I am trying to get the position of a click event on a div. When user clicks somewhere on my div I am trying to return x, y coords.

So far I just have a div and a basic listener:

<div class="heybro" style="width:100px;height:100px;background:black;"></div>

$('.heybro').click(function(){
    alert("something");
});
jcuenod
  • 55,835
  • 14
  • 65
  • 102
mr jorden
  • 89
  • 2
  • 12

2 Answers2

1

Try using the event object in your click handler:

$('.heybro').click(function(e) {
  console.log("click location in page:");
  console.log(e.pageX, e.pageY);
  var offset = $(this).offset()
  console.log("click location in div:");
  console.log(e.pageX - offset.left, e.pageY - offset.top);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="heybro" style="width:100px;height:100px;background:black;"></div>

Take a look at this answer for more detail: https://stackoverflow.com/a/3236129/123415

Community
  • 1
  • 1
jcuenod
  • 55,835
  • 14
  • 65
  • 102
  • Thanks it works, But my `e.pageY` value show like 472 when I click at position 20th. – mr jorden Dec 02 '16 at 17:43
  • O.k I think it's showing the position of the `body` other than my `div` element position, Can you tell me why is it doing that. FYI: I am Using exact same code as you said above. – mr jorden Dec 02 '16 at 17:54
0
    $(".heybro").onclick(function() {
        var $clicker = $(this);
        var pos = $clicker.position();
        console.log(pos.top);
        console.log(pos.left);
    });

Editted to clearly explanation, for anyone who might want to understand how it works.

var $clicker = $(this);

The $clicker variable is initialised, created a new special jQuery object. We need to do so in order to use the second method, jQuery.position, to create a new variable with the top offset and left offset of the click.

var pos = $clicker.position();

We can now access the "top" and "right" properties, which indicate the position where the user clicked, relative to the top and left coordinates.

Karl Buys
  • 439
  • 5
  • 12