Stick HTML element to the top when scrolled through with JavaScript

In this article I’m going to present a lightweight script to stick an HTML element to the top of the page when the user scrolls through it. Use this to make a menu, a call to action button or any other important element always stay in focus. Adjusting the script you can trigger other effects when the page scrolls through an anchor point. Here are the HTML CSS and JS codes to use to accomplish this effect.

javascript stick element top scroll through
Another similar example when we want to attach the section to the bottom of the page.

The HTML Code

.
.
<div id="stick-here"></div>
<div id="stickThis">Sticky note</div>
.
.

We’re adding two elements with the specified IDs: the first is the “sensor”. When this element reaches the top of the page it triggers the sticking of the second element. This will only happen if there’s other content below these elements and they can reach the top of the page.

The Script

function sticktothetop() {
    var window_top = $(window).scrollTop();
    var top = $('#stick-here').offset().top;
    if (window_top > top) {
        $('#stickThis').addClass('stick');
        $('#stick-here').height($('#stickThis').outerHeight());
    } else {
        $('#stickThis').removeClass('stick');
        $('#stick-here').height(0);
    }
}
$(function() {
    $(window).scroll(sticktothetop);
    sticktothetop();
});

The JavaScript checks the distance of the stick-here element from the top of the window and when it’s reached it adds the .stick class to the wrapper element.

The Styles

#stickThis {
    padding: 5px;
    background-color: #ccc;
    font-size: 1.5em;
    width: 300px;
    text-align: center;
    font-weight: bold;
    border: 2px solid #444;
    -webkit-border-radius: 10px;
    border-radius: 10px;
}
#stickThis.stick {
    margin-top: 0;
    position: fixed;
    top: 0;
    z-index: 9999;
    -webkit-border-radius: 0 0 10px 10px;
    border-radius: 0 0 10px 10px;
}

Live demo (jsFiddle)

This CSS code is just a demonstration to show you that there should be a different style for the #stickThis and #stickThis.stick elements. The important part is the position: fixed; top: 0; part of the sticky styles.