Search code examples
jquerycssscrollfixed

How to set a maximum top margin for a fixed element?


So I have this code:

jQuery(document).ready(function($){ 
    $( window ).scroll(function() {
        var current_top = $(document).scrollTop(); 
        var heights = window.innerHeight;
        document.getElementById("sHome").style.height = heights * 0.8 + "px";
        $('#sHome').css('top', (current_top*1));    

    });

});

More precisely I'm reffering to:

$('#sHome').css('top', (current_top*1));

which is setting a top margin equal to scroll.

It's working fine but, when I'm using inspect element I have an infinite scroll so it gets like top: 7000px;

Is there any way to limit this value?

I found a function, Math.max(), but I don't know if it's going to work in my example.

Cheers.


Solution

  • $('#sHome').css('top', Math.min((current_top*1), YOUR_MAXIMUM_VALUE));
    

    should work fine