23
DecToday I’m going to teach you how to add a sticky element to a website. We use a jQuery plugin called pinBox for this. Please remember that we have to use this plugin with jQuery version 1.7 or higher. As below we can add jQuery and this pinBox plugin.
<!-- jQuery -->
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<!-- Include pinBox plugin -->
<script src="js/jquery.pinBox.min.js"></script>
We do not need a special markup for this. But to wrap our sticky element we need a wrapper element or a container element. We give it the id #pinBoxContainer. Also, give a class called .pinBox to our sticky element. Now let’s add our markup as shown below. There is something important to keep in mind. That is, we need to add the “position: relative;” style to our container element.
<!-- container with id -->
<div class="container" id="pinBoxContainer">
<!-- if you don't use bootstrap.css make sure to add [position:relative] if div parent have float property. -->
<div class="col-sm-4">
<!-- box you want to pin inside [id="pinBoxContainer"] have class or id -->
<div class="pinBox">
<h2 class="headColor">Example box</h2>
<p>some text</p>
</div>
</div>
<div class="col-sm-8">
<h2 class="headColor">Example box</h2>
<p>some text</p>
</div>
</div>
The last thing to do is to call the plugin like this.
$(document).ready(function() { $(".pinBox").pinBox({ Top : '50px', Container : '#pinBoxContainer', }); });
Below you can find all the plugin options that we can use.
$(document).ready(function() { $(".pinBox").pinBox({ //default 0px Top : '50px', //default '.container' Container : '#pinBoxContainer', //default 20 ZIndex : 20, //default '767px' if you disable pinBox in mobile or tablet MinWidth : '767px', //events if scrolled or window resized Events : function(e){ console.log(e); // e.current => current scroll top [number] // e.direction => scroll down or up [up,down] // e.width => window width [number] // e.active => if pinBox active [true,false] // e.disabled => if window width < MinWidth pinBox will disabled [true, false] } }); });
If you want to see a demo of how this works, you can go to this link.
Subscribe us and get latest news and updates to your inbox directly.