Social share buttons
Do you see the social share buttons on the bottom left corner? Ok, I’m going to explain how to build them.
It isn’t difficult… so if you don’t want to read you can download the project:
While you are scrolling down you might notice that the buttons stay still until the end of the article, so they only move within the article section.
The HTML and CSS
The code below is a short version of the HTML structure of the article and buttons. To see the full version check the project on Github.
<div class="article-container">
<div class="share-btn">
<!– PLACE YOUR BUTTONS HERE –>
</div>
<div class="article">
<p>Here your article […]</p>
</div>
</div>
The CSS class article-container
identifies the article div and must have the CSS property position:relative
.
The share buttons must be placed in the div with the class share-btn
. The div share-btn
must have the following properties:
position:absolute
top:0
left:0
To move the share buttons we are going to play with the CSS property top
of share-btn
through javascript functions.
The Javascript
When the document is ready, the function setArticleSection()
calculates the boundaries of the article section and saves them in the global variable sectionArticle
:
function setArticleSection() {
// space between the article-container and the top
var top_var = parseInt( $('.article-container’).position().top );
// height of the article-container
var height_var = $('.article-container’).height();
// bottom article limit that the share buttons have not to exceed
var bottom_limit_var = height_var + top_var;
// saving the values in a global variable
window.sectionArticle = {top:top_var , bottom_limit:bottom_limit_var};
}
When you scroll you trigger the function moveShareBtns()
that moves the share buttons (the div with the class share-btn
).
function moveShareBtns() {
// it sums the current vertical position of the scroll bar with the browser window height
// in order to get the bottom position from the top
var bottom = $(window).scrollTop() + window.innerHeight;
// it checks if the browser bottom exceed the article bottom limit
if (window.sectionArticle.bottom_limit > bottom) {
// css_top is the position to assign to the share buttons from the top
var css_top = bottom – window.sectionArticle.top – $('.share-btn’).height();
if (css_top < 0) css_top = 0;
$('.share-btn’).css('top’, (css_top-25) ); // the -25 just to move the buttons a little bit up
}
}
css_top
is the final height to assign to .share-btn
: this is the bottm
without sectionArticle.top
and the share button div height $(‘.share-btn’).height()
_