Home > other >  How to get a changing height value of one element and return it as a CSS "top" value on an
How to get a changing height value of one element and return it as a CSS "top" value on an

Time:09-21

I have a div called "header" that shrinks its height when the user scroll down the page.

Under the "header" I have another div called "menu". I want the menu to be "position absolute" with a "top: xy" value that is the same as the height of the "header", even when it changes.

With:

var height_of_div1 = $(".header").css('height');
$(".menu").css('top',height_of_div1);

...I can dynamically adjust the menu's "top: xy" value based on the initial height of the "header".

But I need to automatically adjust it when the height of the "header" changes.

Can I accomplish it with jQuery?

Thank you so much in advance.

CodePudding user response:

Your jQuery code is correct to fetch header height and use the value to adjust position top. But you need to apply it with scroll listener.

window.addEventListener('scroll',function(){
  var height_of_div1 = $("#header").css('height');
  $('.menu').css('top', height_of_div1)
});
  • Related