Reputation: 169
I am trying to calculate the div positioning. This is my code .
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<style>
.content {width: 60%;
position: relative;
text-align: center ;
top: 150px;
left:300px;
right:450px; border-style: solid;
border-width: 5px;
}
</style>
</head>
<body>
<div class="content">
Testings content
</div>
<script>
function ReadDivPos() {
var content = document.getElementsByClassName('content');
for (i = 0; i < content.length; i++) {
console.log("Top " + content[i].getBoundingClientRect().top) //top
console.log("left " + content[i].getBoundingClientRect().left) //left
console.log("right " + content[i].getBoundingClientRect().right) //right
console.log("offsetWidth " + content[i].offsetWidth); //width
}
var _divPos = "LEft "+content[0].getBoundingClientRect().left + ",Width " + content[0].offsetWidth + ",Avail Width " + window.screen.availWidth + ",Right " + content[0].getBoundingClientRect().right;
return _divPos;
}
console.log(ReadDivPos());
</script>
</body>
</html>
This code works fine when the page is not resized but when the page is resized and horizontal scroll bar appears on the screen then it doesnot work fine. How can i get the exact positions of the div if the page is resized or not. For example these are the images i have captured to explain the problem .
When the page is resized and scroll bar is at the extreme right then left positioning of div shows 208px which is wrong and it should be 311 px .
When i move the scroller on the left and then i calculated the width using Chrome MeasureIT add on then it says 311px.
I want to get the exact positioning of the div.I am using class of the div to get the positioning as i am not using div id and i only had to use the class so this is how i have done it but it is not working when the page is resized. Any help?
Upvotes: 1
Views: 184
Reputation: 1680
Since you already have jQuery loading in the page, take a look at the jQuery offset() and position() methods and leverage jQuery selectors.
<script>
function ReadDivPos(selector) {
var _divPos = "";
$(selector).each(function() {
var p = $(this).offset();
var w = $(this).width();
console.log("Top " + p.top) //top
console.log("left " + p.left) //left
console.log("right " + p.left + w) //right
console.log("offsetWidth " + w); //width
_divPos += "Left " + p.left + ",Width " + w + ",Avail Width " + window.screen.availWidth + ",Right " + (p.left + w) + "\\n";
});
return _divPos;
}
console.log(ReadDivPos(".content"));
</script>
Upvotes: 1