Search code examples
javascriptjqueryoffset

jQuery offset().left vs offsetLeft


Currently I'm trying to speedup my code with refactoring from jQuery to pure JS.

I know that there are some other threads about this, but I couldn't find any which is equals to my problem.

Now I'm at the point where I want to get the same value with offsetLeft instead using offset().left

Does anyone know a simple explanation how to calculate the right value?


Solution

  • You can use the getBoundingClientRect function to get this information:

    console.log(document.getElementById('h1').getBoundingClientRect().left);
    <div>
      A
    </div>
    <h1 id="h1">Test</h1>

    However keep in mind that jquery is pretty optimized, and the code there is probably using exactly the same function, or probably something pretty close.