V
V
v-orlov2018-03-03 13:21:43
JavaScript
v-orlov, 2018-03-03 13:21:43

How to get the height of an element 1 time in javascript?

there is a big header and content under it. when the page scrolls to the bottom border of the header, it becomes smaller and fixed in height.

<header>шапка</header>
<section>контент</section>

but when scrolling, there is a problem with the content jumping up, because the header was 500px, and now it is 0 (actually 50px but fixed). how i try to solve
var height = $('header).height();

$(window).scroll(function () {
if ($(this).scrollTop() > height ) {
        $('header').addClass('stick');
        $('section').css('padding-top', height );
      } else {
        $('header').removeClass('stick');
        $('section').css('padding-top', 0);
      }
});

Of course, this height variable changes when scrolling, as the header itself changes when scrolling. and the solution doesn't work. what am I doing wrong? How can I get this variable once when the page is loaded? and for the scroll function to get this variable without changing it?
Thank you

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton fon Faust, 2018-03-03
@v-orlov

https://jsfiddle.net/anton4ept/xk3sLhj4/
everything works fine and nothing is recalculated.
Apparently, something is not agreed.

V
v-orlov, 2018-03-03
@v-orlov

Thank you all for pointing me in the direction of the error.
Indeed, in the wilds of scripts there was a call function, which is separately tied at this height and additionally sets it with a script (although there is a style). in the developer panel, I didn’t pay attention to the height set by js at all.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question