1

I need to find a way to change css when an element is not on its default position anymore,and when the user scrolls it back , the default css is set back.

Example: I have a fixed header with a height of 30px , and the position of it is top: 0 , when the user scoll down , the height will be 15px , and if the user scroll up and the header gets its initial position of top: 0 , the height will be 30px again.

I tried something like this:

var location = $('#header').offset();
        $( "#header" ).scroll(function() {
           if(location.top!=0){
               $('#header').css({'height': '4vw'});
           }else{
               $('#header').css({'height': '6vw'});
           }
        });
Petru Lebada
  • 2,167
  • 8
  • 38
  • 59
  • w3schools has an example of this: [How TO - Resize Header on Scroll](https://www.w3schools.com/howto/howto_js_shrink_header_scroll.asp) The code is nice and lean. The only drawback is that it's not responsive. I'm trying to customize it at the moment. – Mentalist Apr 10 '19 at 08:34

1 Answers1

2

You can use window on scroll to check scroll possition; You can get scroll Position using $(window).scrollTop()

$(window).on('scroll', function () {
    var scrollTop = $(window).scrollTop();
    if (scrollTop > 50) {
        $('#header').stop().animate({height: "30px"},200);
    }
    else {
         $('#header').stop().animate({height: "15px"},200);   
    }
});

Have a good day...

Bhavin Solanki
  • 4,740
  • 3
  • 26
  • 46