tomsseisums
tomsseisums

Reputation: 13357

Track position on click

How can I track what position have I clicked within an element in percent?

Basicly, it's for a slider... And I want to track the position where to move the needle (CSS left property in %) once the slider has been clicked.

Upvotes: 0

Views: 248

Answers (2)

tomsseisums
tomsseisums

Reputation: 13357

Managed to do this with:

$('#song-seeker').click(function(e){
    var offset = $(this).offset(); // somehow this.offsetLeft didn't work
    var x = Math.floor(e.pageX - offset.left); // calculates pixel value of position clicked within element
    x = Math.floor(x * 100 / $(this).width()); // transform to % value based on full clicked elements width
    // Math.floor() used to prepare values with 0 values behind comma, therefore, CSS safe.
});

Upvotes: 0

Roman
Roman

Reputation: 276

Try this:

<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
   $("#special").click(function(e){
      var xP = e.pageX * 100 / $(e.target).width();
      var yP = e.pageY * 100 / $(e.target).height();
      $('#status2').html(xP +', '+ yP);
   }); 
})
</script>
<body>

<h2 id="status2">
0, 0
</h2>
<div style="width: 100px; height: 100px; background:#ccc;" id="special">
Click me anywhere!
</div>
</body>
</html>

Upvotes: 1

Related Questions