On the last blog I had mentioned the painstaking process of getting my sticky header to function correctly and especially so when accounting for the top margin and mobile scaling. I have provided the code below for the sticky header.
@HostListener('window:scroll', ['$event']) onWindowScroll(e) { if (window.pageYOffset > 251) { let element = document.getElementById('navbar'); element.classList.add('sticky'); element.classList.remove('non_sticky'); if(window.innerWidth <= 850) { this.top_padding_var = 87; } else { this.top_padding_var = 43; } } else { let element = document.getElementById('navbar'); element.classList.remove('sticky'); element.classList.add('non_sticky'); this.top_padding_var = 0; } }
What this is doing, essentially, is adding the sticky header to the document when past a certain point and removing the non-sticky variant. The toolbar is nested inside a non-sticky div, inside the sticky div, which is present at the top of the page below the header. When scrolling past a certain point the non-sticky version is “swapped” for the sticky variant which is fixed to the top of the page. Here below is the code for this sticky component where you can get a better idea of what I mean by nesting.
<header class="animated fadeInDown" id="navbar"> <div class="non_sticky" [ngStyle]="{'height':header_height}"> <app-toolbar></app-toolbar> </div> </header>
You can see here as well that the height of the container for the toolbar is determined by the variable, header_height. I mentioned previously as well that considerations were made for mobile use and this is one. Below is the method that determines this variables value.
resize() { if(window.innerWidth <=850){ this.header_height = 40; } else{ this.header_height = 60; } }
Increasing the height makes readability on mobile more effective as well as providing enough space for the buttons to fit in the bar. Some may have noticed a variable being assigned in addition to the sticky-header being added/removed, which highlights another challenge of this particular bit of styling. As mentioned, the sticky header simply swaps in a fixed version of the normal toolbar, but in doing so this new fixed element has a higher z-index and does not “touch” the other elements.
As a result, this new element naturally covers whatever was behind it just a moment ago. To remedy this, I added this variable to the method to dynamically add padding to push the elements on the page back down where they belong. Honestly, it feels like trickery the way everything works together but when it does its nearly seamless unless you know exactly what to look for. In the next blog I will discuss a part of this element that I did not include previously: animations.
From the blog CS@Worcester – Press Here for Worms by wurmpress and used with permission of the author. All other rights reserved by the author.