top of page

What is getBoundingClientRect? Usage and Examples

Learn element positions and sizes using the JavaScript getBoundingClientRect method. Code examples, DOMRect properties, and practical use cases.

In web development, knowing the exact position of an element on a page forms the basis of many interactive features. Whether you want to display a tooltip, open a dropdown menu, perform drag-and-drop operations, or create scroll animations, you need to know the element's pixel-level location. JavaScript's getBoundingClientRect() method fulfills this need.

This guide will teach you what the getBoundingClientRect() method is, how it works, and when you can use it, along with code examples.


What is getBoundingClientRect()?


`getBoundingClientRect()` is a JavaScript method that returns the position and dimensions of a DOM element within the viewport. This method calculates exactly where the element appears on the screen in pixels and returns the result as a DOMRect object.

The basic use of the method is quite simple:


const element = document.querySelector('.hedef-element');
const rect = element.getBoundingClientRect();

console.log(rect);

When this code runs, the console will display output similar to this:

DOMRect {
  x: 100,
  y: 200,
  width: 300,
  height: 150,
  top: 200,
  right: 400,
  bottom: 350,
  left: 100
}

DOMRect Features


The DOMRect object returned by the getBoundingClientRect() method contains eight properties. Each of these properties provides different information about the position of the element.


Location Features


top: The distance (in pixels) from the top edge of the element to the top edge of the viewport.


left: The distance (in pixels) from the left edge of the element to the left edge of the viewport.


bottom: The distance (in pixels) from the bottom edge of the element to the top edge of the viewport.


right: The distance (in pixels) from the right edge of the element to the left edge of the viewport.


Size Specifications


width: The width of the element (including padding and border)


height: The height of the element (including padding and border)


Alternative Location Features


x: same as left value


y: same as the top value


The image below shows the corresponding views of these features on the viewport:

Viewport (Tarayıcı Penceresi)
┌─────────────────────────────────────────┐
│                  ↑                      │
│                 top                     │
│                  ↓                      │
│     ←left→ ┌──────────┐                 │
│            │          │ ↑               │
│            │  Element │ height          │
│            │          │ ↓               │
│            └──────────┘                 │
│            ←  width   →                 │
│                        ←right→          │
│                                         │
│            ←───bottom (viewport üstünden)│
└─────────────────────────────────────────┘

Basic Usage Examples


Example 1: Obtaining Element Coordinates

The simplest use is to get the instantaneous coordinates of an element:


const kutu = document.getElementById('kutu');
const konum = kutu.getBoundingClientRect();

console.log(`Sol: ${konum.left}px`);
console.log(`Üst: ${konum.top}px`);
console.log(`Genişlik: ${konum.width}px`);
console.log(`Yükseklik: ${konum.height}px`);

Example 2: Checking if an element is visible in the viewport.


To check if an element is visible on the user's screen:


function elementGorunurMu(element) {
  const rect = element.getBoundingClientRect();
  
  return (
    rect.top >= 0 &&
    rect.left >= 0 &&
    rect.bottom <= window.innerHeight &&
    rect.right <= window.innerWidth
  );
}

const hedef = document.querySelector('.kontrol-edilecek');
if (elementGorunurMu(hedef)) {
  console.log('Element ekranda görünüyor');
} else {
  console.log('Element ekran dışında');
}

Example 3: Tooltip Positioning


To display a tooltip when a button is clicked:


const buton = document.querySelector('.tooltip-buton');
const tooltip = document.querySelector('.tooltip');

buton.addEventListener('mouseenter', function() {
  const rect = buton.getBoundingClientRect();
  
  // Tooltip'i butonun hemen altına konumlandır
  tooltip.style.position = 'fixed';
  tooltip.style.left = rect.left + 'px';
  tooltip.style.top = rect.bottom + 5 + 'px'; // 5px boşluk
  tooltip.style.display = 'block';
});

buton.addEventListener('mouseleave', function() {
  tooltip.style.display = 'none';
});

Its Relationship with Scroll


Since getBoundingClientRect() returns the position relative to the viewport, the values change when the page is scrolled. This is an important point because you will get different values for the same element at different scroll positions.

If you want the absolute position from the top of the page, you need to add the scroll value:


const element = document.querySelector('.hedef');
const rect = element.getBoundingClientRect();

// Viewport'a göre konum
const viewportTop = rect.top;
const viewportLeft = rect.left;

// Sayfa başından itibaren mutlak konum
const sayfaTop = rect.top + window.scrollY;
const sayfaLeft = rect.left + window.scrollX;

console.log(`Viewport Top: ${viewportTop}px`);
console.log(`Sayfa Top: ${sayfaTop}px`);

CSS Transform Support


One of the key advantages of the getBoundingClientRect() method is that it takes CSS transform values into account. Even if an element has been transformed using translate, scale, or rotate, it accurately returns its true visual position.


.donmus-element {
  transform: rotate(45deg) scale(1.5) translateX(50px);
}
const donmus = document.querySelector('.donmus-element');
const rect = donmus.getBoundingClientRect();

// Transform uygulanmış haliyle gerçek konum ve boyut
console.log(`Gerçek genişlik: ${rect.width}px`);
console.log(`Gerçek konum: ${rect.left}px, ${rect.top}px`);

This feature is not found in alternative methods like offsetWidth and offsetLeft. They return the values before the transform.


Practical Use Scenarios


Lazy Loading


To load images only when they are close to the viewport:

function lazyLoadKontrol() {
  const gorseller = document.querySelectorAll('img[data-src]');
  
  gorseller.forEach(img => {
    const rect = img.getBoundingClientRect();
    
    // Görsel viewport'a 100px kala yüklemeye başla
    if (rect.top < window.innerHeight + 100) {
      img.src = img.dataset.src;
      img.removeAttribute('data-src');
    }
  });
}

window.addEventListener('scroll', lazyLoadKontrol);

Determining the Orientation of the Dropdown Menu


To make the menu pop up if it's near the bottom of the screen:


function dropdownYonBelirle(tetikleyici, menu) {
  const rect = tetikleyici.getBoundingClientRect();
  const menuYuksekligi = 200; // Tahmini menü yüksekliği
  
  // Altta yeterli alan var mı kontrol et
  const altaAcilabilir = (window.innerHeight - rect.bottom) > menuYuksekligi;
  
  if (altaAcilabilir) {
    menu.style.top = rect.bottom + 'px';
    menu.classList.remove('yukari');
  } else {
    menu.style.bottom = (window.innerHeight - rect.top) + 'px';
    menu.classList.add('yukari');
  }
  
  menu.style.left = rect.left + 'px';
}

Drag-and-Drop Border Control


To ensure the dragged element remains within a specific area:


const suruklenebilir = document.querySelector('.suruklenebilir');
const kapsayici = document.querySelector('.kapsayici');

suruklenebilir.addEventListener('drag', function(e) {
  const kapsayiciRect = kapsayici.getBoundingClientRect();
  const elementRect = suruklenebilir.getBoundingClientRect();
  
  // Sınırlar içinde mi kontrol et
  const solSinir = e.clientX >= kapsayiciRect.left;
  const sagSinir = e.clientX <= kapsayiciRect.right - elementRect.width;
  const ustSinir = e.clientY >= kapsayiciRect.top;
  const altSinir = e.clientY <= kapsayiciRect.bottom - elementRect.height;
  
  if (solSinir && sagSinir && ustSinir && altSinir) {
    // Hareket geçerli, konumu güncelle
  }
});

Performance Tips


Each time getBoundingClientRect() is called, the browser performs a layout calculation. Therefore, there are points to consider in terms of performance.

Caching the Value: If you need the position of the same element multiple times within the same frame, store the result in a variable:


// Kötü - her seferinde yeniden hesaplar
element.getBoundingClientRect().top;
element.getBoundingClientRect().left;
element.getBoundingClientRect().width;

// İyi - tek hesaplama
const rect = element.getBoundingClientRect();
rect.top;
rect.left;
rect.width;

Use Throttle in Scroll Events: Instead of continuously invoking it during scrolls, invoke it at specific intervals.

let sonCalisma = 0;
const bekleme = 100; // 100ms

window.addEventListener('scroll', function() {
  const simdi = Date.now();
  
  if (simdi - sonCalisma >= bekleme) {
    // getBoundingClientRect işlemleri burada
    sonCalisma = simdi;
  }
});

IntersectionObserver Alternative: If you are only performing visibility checks, IntersectionObserver is a more performant alternative.

const observer = new IntersectionObserver((entries) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      console.log('Element görünür oldu');
    }
  });
});

observer.observe(document.querySelector('.hedef'));

Browser Support


`getBoundingClientRect()` is supported in all modern browsers, including Internet Explorer, offering very broad compatibility. Therefore, you don't need to use a polyfill or alternative solution.

Supported browsers include Chrome, Firefox, Safari, Edge, and Opera. Full support is also available for mobile browsers.


Common Mistakes


Error 1: Assuming the values are static.

getBoundingClientRect() returns a current value. The values will be different after scrolling, resizing, or DOM changes. Call it again whenever you need to.


Error 2: Forgetting the document scroll position.

If you want the position to start from the top of the page, don't forget to add the window.scrollY and window.scrollX values.


Error 3: Using hidden elements

For elements with `display: none`, `getBoundingClientRect()` returns zero. The element must be visible.


const gizli = document.querySelector('.gizli'); // display: none
const rect = gizli.getBoundingClientRect();
// rect.width = 0, rect.height = 0

`getBoundingClientRect()` is the most reliable method for element positioning in JavaScript. It allows you to retrieve position and size information relative to the viewport with a single call. Its ability to account for CSS transform values and its extensive browser support make it indispensable in many scenarios such as tooltips, dropdowns, lazy loading, and drag-and-drop.


The top, left, width, height, right, and bottom properties in the DOMRect object returned by the method help you determine the exact position of any element on the page. Remember to cache the values and use throttles in scroll events for better performance.


Frequently Asked Questions


What is the difference between getBoundingClientRect() and offsetTop?

`offsetTop` returns the position of an element relative to its closest positioned parent. `getBoundingClientRect()` returns the position relative to the viewport and takes CSS transform values into account.


Can getBoundingClientRect() return a negative value?

Yes. Top and left can be negative signs if the element is above or to the left of the viewport. This happens when the element scrolls off the screen.


Does calling getBoundingClientRect() in every frame affect performance?

Continuously calling this for a large number of elements can lead to layout thrashing. Using it within a `requestAnimationFrame` and caching the results improves performance.


For professional support in web development and JavaScript, contact Blakfy: blakfy.com/iletisim

Blakfy Customer Relations Specialist

Blakfy Expert

bottom of page