When a visitor scrolls down your blog to view more content, the upper portion of your blog goes out the window from the top to make way for the lower portion that enters from the bottom.
Now what we are going to do is stick your chosen widget to the top edge of the window as it is about to leave, thus making the widget visible at all time while the visitor scrolls. It will float there until its original location comes back when the page is scrolled back up.
This trick is applicable to any widget or element that has an ID, regardless of its location on your blog. It is perfect for navigation bar, subscription box and social media sharing buttons.
See it in action, scroll down this post and keep your eyes on the top menu bar.
How to install
- Paste the following code above the
</body>
tag in your template.
Or if you prefer not to touch the template, you can simply paste it in a HTML/Javascript (in Blogger) or a Text widget (in WordPress). If you choose this route, make sure you position this widget below (after) the widget that you want to make sticky.01
<
script
>
02
// Sticky widget by Bloggersentral.com
03
// Tutorial at http://www.bloggersentral.com/2013/04/how-to-make-any-widget-sticky.html
04
// Free to use or share, but please keep this notice intact.
05
//
<![CDATA[
06
bs_makeSticky("YOUR_WIDGET_ID"); // enter your widget ID here
07
function bs_makeSticky(elem) {
08
var bs_sticky = document.getElementById(elem);
09
var scrollee = document.createElement("div");
10
bs_sticky.parentNode.insertBefore(scrollee, bs_sticky);
11
var width = bs_sticky.offsetWidth;
12
var iniClass = bs_sticky.className + ' bs_sticky';
13
window.addEventListener('scroll', bs_sticking, false);
14
function bs_sticking() {
15
var rect = scrollee.getBoundingClientRect();
16
if (rect.top < 0) {
17
bs_sticky.className = iniClass + ' bs_sticking';
18
bs_sticky.style.width = width + "px";
19
} else {
20
bs_sticky.className = iniClass;
21
}
22
}
23
}
24
//]]>
25
</
script
>
26
27
<
style
>
28
.bs_sticking {background:#f2f2f2 !important; position:fixed !important; top:0; z-index:9999; box-shadow:0px 10px 4px -5px rgba(0,0,0,0.3); margin-top: 0; position:relative\9 !important;}
29
</
style
>
- Get the ID of the widget or element you want to make sticky and enter it in line 6 (replacing "YOUR_WIDGET_ID"). For example let's say the widget ID is HTML9, then code line 6 would become:
bs_makeSticky("HTML9");
- Preview before saving.
Styling
- Styling for the sticky widget while it's sticking can be applied in line 28.
- Background and box-shadow are optional. However you might want to keep the background (and replace the color to match your sidebar's). Most templates do not assign a background to widgets meaning you can see the content scrolling in the background.
Enjoy!