Script To Stick HTML Element To The Top When Scrolled

In this article, I’m going to give a lightweight script to paste an HTML detail to the top of the web page when the person scrolls thru it. Use this to make a menu, a name to movement button or some other crucial detail usually stay in consciousness. Adjusting the script you can trigger different results while the web page scrolls through an anchor factorhere are the HTML CSS and JS codes to use to perform this effect.

The HTML Code

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

We’re including factors with the specified IDs: the primary is the “sensor”. while this element reaches the pinnacle of the page it triggers the sticking of the second one detailthis may best occur if there’s different content material underneath these elements and they can reach the pinnacle of the web page.

The Script

function sticktothetop() {
    var window_top = $(window).scrollTop();
    var top = $('#stick-here').offset().top;
    if (window_top > top) {
    } else {
$(function() {

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;

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

We hope you like this post!

Please follow and like us:

Leave a Comment

Your email address will not be published. Required fields are marked *