Javascript Floating div that always ontop when scrolls down

10,470

With the class or id of the element you want to keep on top you should apply some CSS rules,

for example, if your element class is .topnavigation

you could do the following in jQuery

<style>
.topnavigation {
    width:;/* add the width here */
    position:static;
}
.topnavigation.scrolling {
    position:fixed;
    top:0px;
}
</style>
<script>
$(window).scroll(function () { 
    if($(this).scrollTop() > 50) // change 50 to what you want (work out how far the nav is from the top of the page alraedy and add it there, that'll make it smoother transition)
    {
        $('.topnavigation').addClass('scrolling');
    } else {
        $('.topnavigation').removeClass('scrolling');
    }
});
</script>

If you can't use jQuery you could do the following with normal javascript:

Updated: 06 Jan 2017 I've updated this to use the document.querySelector and Element.classList methods. All modern browsers and IE 10 > support these methods.

window.addEventListener('scroll',checkPosition,false);
function checkPosition()
{
    // #theid or #theclass or standard element selector
    var xNAV = document.querySelector("#topnav"); 
    if(window.scrollY > 50)
    {
        xNAV.classList.add("scrolling");
    } else {
        xNAV.classList.remove("scrolling");
    }
}
Share:
10,470
user63898
Author by

user63898

developer

Updated on June 04, 2022

Comments

  • user63898
    user63898 almost 2 years

    What is the right way to build simple floating divs using Javascript (or CSS programmatically) that is on top and always visible when scrolling down?

    Now I've seen examples like this. When you scroll down you see the div jumping and a delay. I want it to constantly be on top when the content of the page is not my ,
    the script will be injected via chrome extention

    can it be done? something like this ; but less complex and not depend on the page content