Chau Chun
Chau Chun

Reputation: 105

Cant get offset of div

this is my getoffset js code to get div width and left

  var objRedPacketDivStyle = document.getElementById("styRedPacketAppear");
        var objOffset = objRedPacketDivStyle.offset();
        var intWidth = objOffset.offsetWidth;
        var objWidthStart = objOffset.offset.left;
        var objWidthEnd = objWidthStart + intWidth;
        alert(objWidthStart + objWidthEnd);

and here is my div and css

<div class="styRedPacketAppear" id="styRedPacketAppear"></div>

#styRedPacketAppear {
position: fixed;
top: 0;
left: 0;
width: 100%;
z-index: 98;
pointer-events: none;
}

Upvotes: 1

Views: 1243

Answers (2)

Nick Parsons
Nick Parsons

Reputation: 50759

This isn't working as .offset() is a jQuery method. Since you don't have jquery you need to use vanilla javascript to achieve this.

You can use:

  • element.offsetWidth: "returns the layout width of an element as an integer." - MDN
  • element.offsetLeft: "returns the number of pixels that the upper left corner of the current element is offset to the left within the HTMLElement.offsetParent node." - MDN

Using these two properties will resolve your issue:

var objRedPacketDivStyle = document.getElementById("styRedPacketAppear");
// Remove this: var objOffset = objRedPacketDivStyle.position.offset();
var intWidth = objRedPacketDivStyle.offsetWidth;
var objWidthStart = objRedPacketDivStyle.offsetLeft;
var objWidthEnd = objWidthStart + intWidth;
alert(objWidthStart + objWidthEnd);
#styRedPacketAppear {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 98;
  pointer-events: none;
}
<div class="styRedPacketAppear" id="styRedPacketAppear"></div>

Upvotes: 4

Mohit Verma
Mohit Verma

Reputation: 1

The offsetTop property returns the top position (in pixels) relative to the top of the offsetParent element. The returned value includes: -the top position, and margin of the element -the top padding, scrollbar and border of the offsetParent element.

#test {
  top: 100px;
  margin: 10px;
  padding: 10px;
  width: 300px;
  position: fixed;
  border: 5px solid black
}

var testDiv = document.getElementById("test");
document.getElementById("demo").innerHTML = testDiv.offsetTop;

Result-offsetTop is: 110

Upvotes: 0

Related Questions