TheShinePL
TheShinePL

Reputation: 61

Jquery - .offset().left() - percentage

I have:

var offset = $(this).offset();
    var relativeX = e.pageX - offset.left;

This return value of pixels..

How do, return value of percentage?

Upvotes: 0

Views: 3943

Answers (2)

Luigi Siri
Luigi Siri

Reputation: 2018

If you get the width of the element you want to get the percentage from.

html:

<div class="test"></div>

JS:

$(document).on('click','.test', function(e){
    var offset = $(this).offset();
    var relativeX = e.pageX - offset.left;
    var wide = $('body').width();
    var percent = (relativeX*100)/wide;
    alert(percent);
});

CSS:

.test{
  background-color: #000000;
  width: 100%;
  height: 50px;
}

See it live here.

Hope it helps you.

Upvotes: 2

Carlos Calla
Carlos Calla

Reputation: 6716

$(this).offset().top and $(this).offset().left return integers and your e.pageX I will asume it is an integer. In this case you can't. You can then get the percentage the substraction of these values represent but the operation var relativeX = e.pageX - offset.left; will return an integer.

Upvotes: 1

Related Questions