Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery offset is returning the wrong value

Tags:

jquery

offset

I have a collapsed sidebar (using bootstrap), and I'm trying to make sure the collapsed element is scrolled to whenever it is made visible.

In order to do that I'm using offset() by jQuery which returns 0 the first click and returns the correct offset on the second click.

Here's my code:

    $.each($('[data-toggle="collapse"]'), function() {
        $(this).on("click", function() { 
            if ($(this).is('A')) { 
                event.preventDefault(); $(this).toggleClass("active");
                var x = $(this).attr("href");
                console.log($(x).offset().top)

            }
        })
    })
like image 744
elad.chen Avatar asked Feb 28 '26 09:02

elad.chen


1 Answers

Items set to display: none are outside of the page flow, meaning they take up no space within the page. This means that whilst they are set to display: none, they have no offset values.

On the first click, the browser tries to find the offset, which is 0 and then shows the element. As soon as the element is displayed, an offset left/top value is given.

Example Fiddle

like image 149
Adam Botley Avatar answered Mar 01 '26 21:03

Adam Botley