Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

offsetTop return 0

I'm trying to develop a function which move a div-Element to the same height as the hovered element. For this I used offsetTop but it always returns 0 and I don't get what I'm doing wrong.

$( document ).ready(function() {
            const handle = document.querySelector('#handle');


            const headers = document.querySelectorAll('.et_pb_accordion_item_0, .et_pb_accordion_item_1, .et_pb_accordion_item_2')
                .forEach(el => {
                  el.addEventListener('mouseover', e => {
                      handle.style.top = `${e.currentTarget.offsetTop}px`;
                });
            });
        });

I also tried to use getBoundingClientRect().top but it return different values if I scroll dwon

like image 890
ThinkCode Avatar asked Mar 20 '26 14:03

ThinkCode


1 Answers

You should use the getBoundingClientRect() as follow:

var ele = document.getElementById('elementId');
var offset = ele.getBoundingClientRect();
// you can use
offset.left;
offset.top;

It works for me.

like image 88
Trung Avatar answered Mar 23 '26 03:03

Trung



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!