Fixed Sidebar Element and Sticky Floating Bar while Scrolling: jQuery

Fixed Sidebar Element and Sticky Floating Bar while Scrolling

What I’m creating here is a fixed sidebar element and a sticky floating bar while scrolling the page. To make it an easy task, I use jQuery library. First of all let’s see what we need exactly.

Fixed sidebar element,

  • Not the whole sidebar-just an element and it’s not the last element.
  • When I scroll and reach the end of the sidebar, the element must appear.

Floating Bar,

  • When reach a certain point while scrolling, the bar must appear.
  • I could be completely different one or already existing one.

Visit the demo page and pay attention to the ad at the top of right side bar while scrolling. Also check the sharebar.

How to create a fixed sidebar element using jQuery

First we create our element inside a sidebar with other contents and add a class which will toggle with the original class. I’m using class attribute over id because you can add multiple elements if you need.

01. Add styles to element
02. Add styles to an extra class named fixed_element (We are going to add this class to our element_to_fix div)

Most importantly we must import jQuery library too.

Okay, now let’s start making our element sticky.
01. We use .scroll() function to trigger scrolling.
02. Then sse .offset() method to get current coordinates of the sidebar.
03. Calculate the height of the sidebar and height to the top of the sidebar together and trigger when scrolling exceed the total height we add the .fixed_element class to .element_to_fix class.

How to create a sticky floating bar using jQuery

This is the same as previous one. In this example we change the style of an element instead of adding or toggling a class. But you can use the same method as earlier or vice versa to get the job done. You can add a social share bar or a menu bar or a visitor notice or any element using this. It doesn’t need to be a bar.

First we create our element. In this example, I create a sharebar with basic styles. The most important part is set the display attribute to none. display: none;

Then we decide when we need the bar to appear. In this example, I want my share bar to appear when the content div starts.

That’s it. Now let’s see the full code with both sidebar element and bar.