how to set the position of element to fixed on scroll to certain height and make it normal when not that height?

533 Views Asked by At

I have a div called cop which has a fixed position.

That div should behave same as the questions tab (which is similar) but it is changing its position when page is scrolled .

My Script


     $(window).scroll(function()
{
    var top = 100 * $(window).scrollTop() / ($(document).height() - $(window).height());
    if (top > 40)
    {
        $(".cart, .top").fadeOut();
    }
    else
    {
        $(".cart, .top").fadeIn();      
    }
});
1

There are 1 best solutions below

0
zero point On BEST ANSWER

I have created a working example on CODEPEN. It is easier to understand it in action. First you need to read the scroll event where you can take action on your desired element:

$(window).scroll(function() {
   currentTop = $("body").scrollTop();

   if (currentTop > 300) {
     $(".cop").addClass("copChange");
   } else {
     $(".cop").removeClass("copChange");
   }

});

When you scroll more than 300px in this example, your .cop div will acquire relative position instead of fixed. It will return to original setting when you scroll up. I attempted by different CSS class since it will be easy for you to change styling in any way you want.