Skip to content Skip to sidebar Skip to footer

How To Implement Auto Fixing A Div Like Https://www.yahoo.com

In Yahoo website, when scroll down, a blue part is fixed to the top, while if not scroll down, the blue part is not fixed. How to implement this ? May I try onScroll function?

Solution 1:

I use inspect element and, apperantly it changes class when that "blue part" is not in view, so what it is doing (I guess) is changing the classes while it is in view and not in view, you can find if a div is in view and then change accordingly, "onscroll" is a great idea


Solution 2:

Use $(window).scroll(function() on the part which you want to be fixed.

Fiddle Demo : Demo

$(window).scroll(function(){
    if ($(window).scrollTop() >= 100) {
       $('.sticky-header').addClass('fixed');
    }
    else {
       $('.sticky-header').removeClass('fixed');
    }
});

If you want to apply the fixed part to the header replace the class name in the $(window).scroll(function(){}): function.

Example for fixed Header while scrolling : Demo-2


Solution 3:

You can make it fixed just with css.

<div id="myHeader">Header stuff</div>

#myHeader {
  position: fixed;
  top: 0;
  width: 100%;
  z-index: 1000;
}

Solution 4:

Yes, you need to bind to win scroll like this:

var element = $(YOURTOPELEMENT)
    $(window).scroll(function () {
        var scrollTop = $(window).scrollTop();
        if (scrollTop > element.offset().top) {
            element.css({
                position: "fixed",
                top: 0
            })
        } else {
            element.css({
                position: "relative"
            })
        }
    })

Post a Comment for "How To Implement Auto Fixing A Div Like Https://www.yahoo.com"