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)
}
})
})
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With