Skip to content

Instantly share code, notes, and snippets.

@jaamaalxyz
Created December 10, 2018 11:41
Show Gist options
  • Save jaamaalxyz/e3566e843ae2857a2a04dd69b059a6ac to your computer and use it in GitHub Desktop.
Save jaamaalxyz/e3566e843ae2857a2a04dd69b059a6ac to your computer and use it in GitHub Desktop.
// Example website: https://www.marksandspencer.com
// Rules: Display the sticky header when "add to bag" button is not visible in the browser viewport
// and make it work the same way as the main "add to bag" button functionality.
// CSS send to the head
var css = '#btn-group{display:flex;align-items:center;}#prod-price{margin: 0 20px;font-size:1.5rem;font-weight:bold;}#product-header{visibility:hidden;z-index:99999;position:fixed;top:0;display:flex;flex-direction:row;justify-content:space-around;align-items:center;background: #e4e4e4;width:100%;}';
var head = document.getElementsByTagName('head')[0];
var s = document.createElement('style');
s.setAttribute('type', 'text/css');
if (s.styleSheet) { // IE
s.styleSheet.cssText = css;
} else { // the world
s.appendChild(document.createTextNode(css));
}
head.appendChild(s);
// initial variables
var prodName = document.querySelector('.product-header__property.base-text');
var prodPrice = document.querySelector('.price-header__price.ng-binding');
var cartBtn = document.querySelector('#add-to-basket-button');
// sticky header
function stickyHeader() {
var html = `
<nav id="product-header">
<h3 id="product-name">${prodName.textContent}</h3>
<div id="btn-group">
<p id="prod-price">${prodPrice.textContent}</p>
<button type="submit" class="add-to-bag btn btn--primary ttip--init ng-binding disabled" aria-describedby="legalMsg add-to-bag-tooltip" ng-class="{ 'disabled' : (!productCtrl.data.selectedSku || productCtrl.data.selectedSku.inventory.isOutOfStock), 'add-to-bag--added': productCtrl.isAddedToBag() }" data-disabled-return-false="" ng-init="productCtrl.addText = 'Add to bag'; productCtrl.addedText = 'added to bag';" ng-bind="productCtrl.updateAtbText()">Add to bag</button>
</div>
</nav>
`;
// applied sticky navbar content and scroll function
document.body.innerHTML=html+document.body.innerHTML;
window.onscroll = function() {scrollFunc()};
// scroll down to visible sticky header
function scrollFunc() {
var productHeader = document.getElementById("product-header");
var btnPos = document.getElementById('add-to-basket-button').getBoundingClientRect().top
if (btnPos < (0 - document.getElementById('add-to-basket-button').offsetHeight) ) {
productHeader.style.visibility = "visible";
} else {
productHeader.style.visibility = "hidden";
}
}
}
stickyHeader();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment