0

Using the mdbootstrap I have navbar:

<nav class="navbar navbar-expand-lg white">

And it is positioned like this: enter image description here

While scrolling I add the 'fixed-top' class to the navbar with this script:

let nav = $('.navbar').offset().top;
$(window).bind('scroll', function () {
    if  ($(window).scrollTop() >= nav)  {
        $('.navbar').addClass('fixed-top');
    } else {
        $('.navbar').removeClass('fixed-top');
    }
});

This works but: I want to animate the transition between the original and the fixed-top state. I tried with setting a transition time to .navbar{} but it does not work. Do I need to wrap the navbar into another div?

Trojan
  • 485
  • 4
  • 20
  • 1
    `let nav = $('.navbar').offsetTop;` get nav offsettop and depending on its value... do this.. `if ($(window).pageYOffset >= nav) { $('.navbar').addClass('fixed-top'); }` I hope you get offsettop like that.. lil weak in Jquery :D – Himanshu Bansal May 07 '18 at 07:56
  • Thanks for that. But I think you get the offset with offset().top; in jQuery. – Trojan May 07 '18 at 08:08
  • oh ok.. give it a try.. if it works :) .. lemme know if it works or not :D – Himanshu Bansal May 07 '18 at 08:09
  • It works and sets the class like it should do. But there is still no way for me to animate the transition. – Trojan May 07 '18 at 08:16
  • What kind of animation you need.. give me an idea so I can help you better – Himanshu Bansal May 07 '18 at 08:17
  • Currently it just instantly pops to the top of the page. I want it to expand until its just as wide as the screen. – Trojan May 07 '18 at 08:24
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/170535/discussion-between-himanshu-bansal-and-trojan). – Himanshu Bansal May 07 '18 at 12:20

1 Answers1

3
let nav = $('.navbar').offset().top;

Make a variable to store the offset and then update the condition for setting .fixed-top

if ($(window).scrollTop() >= nav) { 
    $('.navbar').addClass('fixed-top'); 
}

To animated:

Add a new class along with .navbar-default, say animate

.animate{
    transition: top 1s ease-in-out;
}

it will add an ease-in-out animation to the navbar.

1s is the time for animation, you can increase or decrease depending on your requirement.

Himanshu Bansal
  • 2,003
  • 1
  • 23
  • 46