jQuery Dimensions and Position
jQuery has methods to read and set the size and the position of elements, and the scroll position of the page. All of them return numbers without the “px” unit.
Note: these methods need a real browser layout engine. Our test tool has no layout, so the code of this chapter is not run here, and the values in the comments are examples of what you may see in a browser.
Dimensions: width and height
<div id="box" style="width:200px; height:100px; padding:10px; border:5px solid black; margin:20px;">Box</div>
$('#box').width(); // 200 content width
$('#box').height(); // 100 content height
$('#box').innerWidth(); // 220 content + padding
$('#box').innerHeight(); // 120
$('#box').outerWidth(); // 230 content + padding + border
$('#box').outerHeight(); // 130
$('#box').outerWidth(true); // 270 also adds the margin
| Method | Includes |
|---|---|
width(), height() | Content only |
innerWidth(), innerHeight() | Content and padding |
outerWidth(), outerHeight() | Content, padding and border |
outerWidth(true) | Content, padding, border and margin |
Set the size
$('#box').width(300);
$('#box').height(150);
$('#box').width('50%');
$('#box').width('+=20'); // relative
Size of the window and the document
$(window).width(); // width of the browser window (viewport)
$(window).height(); // height of the window
$(document).height(); // height of the full page
Position: offset() and position()
| Method | Returns |
|---|---|
.offset() | Position of the element relative to the whole document, as an object with top and left |
.position() | Position relative to the offset parent (the closest positioned parent) |
var pos = $('#box').offset();
console.log(pos.top, pos.left);
var rel = $('#box').position();
console.log(rel.top, rel.left);
$('#box').offset({ top: 100, left: 50 }); // set the position
Scroll position
$(window).scrollTop(); // how many pixels the page is scrolled down
$(window).scrollLeft();
$(window).scrollTop(0); // jump to the top
Smooth scroll to an element
$('#go').on('click', function () {
$('html, body').animate({
scrollTop: $('#target').offset().top
}, 600);
});
Show a “back to top” button after scrolling
$(window).on('scroll', function () {
if ($(this).scrollTop() > 300) {
$('#top-btn').fadeIn();
} else {
$('#top-btn').fadeOut();
}
});
Note:
For scroll and resize events, the browser fires them very often. Keep the code inside light, or limit how often it runs. Next: Traversing: Ancestors.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |