Making a sticky header work - javascript

I've got the following code for a sticky header, but I can't get the scroll to work and it's not a smooth transition. The #top-nav-wrapper barely scrolls when the fixed header below is activated:
<script>
$(document).scroll( function() {
var value = $(this).scrollTop();
if ( value > 48 ) {
$(".header").css("position", "fixed");
$("body").css("padding-top", "90px");
} else {
$(".header").css("position", "relative");
$("body").css("padding-top", "0");
}
});
</script>
The 48 value is the height of the #top-nav-wrapper, plus it has a box-shadow.
The .header class with the search bar is what should remain.
The basic html:
<div class="headerWrapper">
<div id="top-nav-wrapper"></div>
<div class="header"></div>
</div>
The CSS:
body {
background: #EEE;
}
#top-nav-wrapper {
width: 100%;
position: relative;
box-shadow: 0px 1px 1px 0px #B8B8B8;
z-index: 2001;
background: #EEE;
}
.header {
position: relative;
left: 0;
top: 0;
width: 100%;
min-height: 90px;
z-index: 2000;
background: #EEE;
height: 90px;
box-shadow: 0px 1px 2px #C4C4C4;
}
* I tried the following suggestion, but it's the same effect as before:
<script>
$(window).scroll( function() {
var value = $(this).scrollTop();
var $body = $('body');
var docked = $body.hasClass('docked');
if ( value > 48 ) {
if( !docked ) {
$body.addClass('docked');
}
} else {
if( docked ) {
$body.removeClass('docked');
}
}
});
</script>
Any ideas appreciated.
Update - I've changed the script to the following and placed it in the head - this resolves the top nav not scrolling dynamically and I added a placeholder div after the header and before the content with the same size height as the fixed header to keep the content where it should be (because the fixed header changes the natural flow), but there's still the lag/jump when the fixed header kicks in.
Placeholder CSS:
.headerPlaceholder {
height: 90px;
width: 100%;
display: none;
}
Solution to top nav not scrolling all the way after 48px scroll height was set:
<script>
$(document).ready(function () {
var div = $('.header');
var div2 = $('.headerPlaceholder');
var start = $(div).offset().top;
$.event.add(window, "scroll", function () {
var p = $(window).scrollTop();
$(div).css('position', ((p) > start) ? 'fixed' : 'static');
$(div).css('top', ((p) > start) ? '0px' : '');
$(div2).css('display', ((p) > start) ? 'block' : 'none');
});
});
</script>
To make it a smooth transition, there might need to be a slight delay and fadein/out effect, if anyone could help with that?

You can try
$(window).scroll( function() {
var value = $(this).scrollTop();
var $body = $('body');
var docked = $body.hasClass('docked');
if ( value > 48 ) {
if( !docked ) {
$body.addClass('docked');
}
} else {
if( docked ) {
$body.removeClass('docked');
}
}
});
CSS
.docked {
padding-top: 90px;
}
.docked .header {
position: fixed;
z-index: 2005;
}
You can be more efficient if there is an overall container you can target instead of body.

Related

Svelte - hide and show nav on scroll

I want the nav to hide scrolling down 60px and to show when scrolling up 60px, no matter in which part of the page.
I did this, but it's incomplete, what am I missing?
<script>
let y = 0;
</script>
<svelte:window bind:scrollY="{y}" />
<nav class:hideNav={y > 60}>
<ul>
<li>link</li>
</ul>
</nav>
<style>
nav {
position: fixed;
top: 0;
}
.hideNav {
top: -70px;
}
</style>
Your code seems to perfectly hide the navbar after you scroll the specified amount, here is a REPL of your code in action. maybe the body of your content has no scroll ?
here is another implementation REPL that further elaborates how to use scrolling position
<script>
import {onMount, onDestroy} from 'svelte'
const scrollNavBar = 60
let show = false
onMount(() => {
window.onscroll = () => {
if (window.scrollY > scrollNavBar) {
show = true
} else {
show = false
}
}
})
onDestroy(() => {
window.onscroll = () => {}
})
</script>
<style>
.scrolled {
transform: translate(0,calc(-100% - 1rem))
}
nav {
width: 100%;
position: fixed;
box-shadow: 0 -0.4rem 0.9rem 0.2rem rgb(0 0 0 / 50%);
padding: 10px;
transition: 0.5s ease
}
:global(body) {
margin: 0;
padding: 0;
height: 200vh;
}
</style>
<nav class:scrolled={show}>
elemnt
</nav>
In your REPL, it seems like the nav does not reappear on scrolling up. It does appear only at the top of the page.
I am also trying to show the nav when the user scrolls up by 30px anywhere on the page, for instance. I think that it was what OP is asking as well.
I found a REPL successfully doing it with jQuery but I am struggling to make it work in Svelte at the moment. Any clue?
I will revert back if I succeed.
// Hide Header on on scroll down
var didScroll;
var lastScrollTop = 0;
var delta = 5;
var navbarHeight = $('header').outerHeight();
$(window).scroll(function(event){
didScroll = true;
});
setInterval(function() {
if (didScroll) {
hasScrolled();
didScroll = false;
}
}, 250);
function hasScrolled() {
var st = $(this).scrollTop();
// Make sure they scroll more than delta
if(Math.abs(lastScrollTop - st) <= delta)
return;
// If they scrolled down and are past the navbar, add class .nav-up.
// This is necessary so you never see what is "behind" the navbar.
if (st > lastScrollTop && st > navbarHeight){
// Scroll Down
$('header').removeClass('nav-down').addClass('nav-up');
} else {
// Scroll Up
if(st + $(window).height() < $(document).height()) {
$('header').removeClass('nav-up').addClass('nav-down');
}
}
lastScrollTop = st;
}
The answers here couldn't help me. So here's a REPL I made for what I'm using to achieve this in svelte:window.
How I did it;
Create a variable that will store the scroll position (in px) at the end of the scroll event - [let's call it lastScrollPosition].
let lastScrollPosition = 0
At the beginning of a scroll event; inside svelte:window, get and compare the current scroll position to the last scroll position variable we created in [1.] (lastScrollPosition)
<svelte:window on:scroll={()=>{
var currentScrollposition = window.pageYOffset || document.documentElement.scrollTop; //Get current scroll position
if (currentScrollposition > lastScrollPosition) {
showNav = false
}else{
showNav = true
}
lastScrollPosition = currentScrollposition;
}}></svelte:window>
If current scroll Position is greater than lastScrollPosition, showNav is false else, true.
NB: You can use CSS or Svelte Conditional ({#if}) to achieve the hide on scroll down and show on scroll up (This example shows CSS..).
<main>
<div class="nav {showNav == true? "show": "hide" }" >
Nav bar
</div>
<div class="content">
Content
</div>
</main>
<style>
.nav{
background-color: gray;
padding: 6px;
position: fixed;
top: 0;
width: 100%;
}
.content{
background-color: green;
margin-top: 25px;
padding: 6px;
width: 100%;
height: 2300px;
}
.hide{
display: none;
}
.show{
display: unset;
}
</style>

Stop fixed element scrolling at certain point

I have fixed sidebar which should scroll along with main content and stop at certain point when I scroll down. And vise versa when I scroll up.
I wrote script which determines window height, scrollY position, position where sidebar should 'stop'. I stop sidebar by adding css 'bottom' property. But I have 2 problems with this approach:
When sidebar is close to 'pagination' where it should stop, it suddenly jumps down. When I scroll up it suddenly jumps up.
When I scroll page, sidebar moves all the time
Here's my code. HTML:
<div class="container">
<aside></aside>
<div class="content">
<div class="pagination"></div>
</div>
<footer></footer>
</div>
CSS:
aside {
display: flex;
position: fixed;
background-color: #fff;
border-radius: 4px;
transition: 0s;
transition: margin .2s, bottom .05s;
background: orange;
height: 350px;
width: 200px;
}
.content {
display: flex;
align-items: flex-end;
height: 1000px;
width: 100%;
background: green;
}
.pagination {
height: 100px;
width: 100%;
background: blue;
}
footer {
height: 500px;
width: 100%;
background: red;
}
JS:
let board = $('.pagination')[0].offsetTop;
let filterPanel = $('aside');
if (board <= window.innerHeight) {
filterPanel.css('position', 'static');
filterPanel.css('padding-right', '0');
}
$(document).on('scroll', function () {
let filterPanelBottom = filterPanel.offset().top + filterPanel.outerHeight(true);
let bottomDiff = board - filterPanelBottom;
if(filterPanel.css('position') != 'static') {
if (window.scrollY + window.innerHeight - (bottomDiff*2.6) >= board)
filterPanel.css('bottom', window.scrollY + window.innerHeight - board);
else
filterPanel.css('bottom', '');
}
});
Here's live demo on codepen
Side bar is marked with orange background and block where it should stop is marked with blue. Than you for your help in advance.
I solved my problem with solution described here
var windw = this;
let board = $('.pagination').offset().top;
let asideHeight = $('aside').outerHeight(true);
let coords = board - asideHeight;
console.log(coords)
$.fn.followTo = function ( pos ) {
var $this = this,
$window = $(windw);
$window.scroll(function(e){
if ($window.scrollTop() > pos) {
$this.css({
position: 'absolute',
top: pos
});
} else {
$this.css({
position: 'fixed',
top: 0
});
}
});
};
$('aside').followTo(coords);
And calculated coordinates as endpoint offset top - sidebar height. You can see solution in my codepen

Show/hide div on scroll with JQuery WordPress

I have a div with a social bar at the bottom of the screen on my site but I want to display it only after the user scrolls a little and hide it once the user is about to reach the footer. So around 200px before the page ends.+
This is my div:
<div class="sticky-bar-hr">
.......
</div>
This is my CSS:
.sticky-bar-hr{
display: none;
}
And this is the JQuery I am trying:
<script>
$(document).scroll(function() {
var y = $(this).scrollTop();
if (y > 800) {
$('.sticky-bar-hr').fadeOut();
} else {
$('.sticky-bar-hr').fadeIn();
}
});
</script>
But it does not work. The problem seems to be that the function is not being called. I am setting the script in my homepage HTML in Wordpress
Any help?
Thanks in advance
Try this
$(window).scroll(function() {
var y = $(this).scrollTop();
if(y<200) {
$('.sticky-bar-hr').fadeOut();
}
if (y > 200) {
$('.sticky-bar-hr').fadeIn();
}
if(y+ $(this).height() == $(document).height()) {
$('.sticky-bar-hr').fadeOut();
}
});
body {
height: 2000px;
}
.sticky-bar-hr {
position:fixed;
bottom: 0;
width: 100%;
height: 50px;
background:#000;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="sticky-bar-hr">
This is because you have inverted fadeIn and fadeOut.
Here is a working snippet:
$(document).scroll(function() {
var y = $(this).scrollTop();
if (y > 800) {
$('.sticky-bar-hr').fadeOut();
} else {
$('.sticky-bar-hr').fadeIn();
}
});
.sticky-bar-hr{
display: none;
position: fixed;
bottom: 0;
left: 0;
right: 0;
height: 30px;
background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="sticky-bar-hr">
.......
</div>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>

Horizontal scroll at the middle of the page

I want to change the scroll direction at the middle of the page.
I tried to do it with "jInvertScroll", but this plugin increase left in css, like that:left: /* increase on scroll */ px ;
So if I want to change the scroll direction to the middle of the page, left will already have a value like:left: -1500px;
That's my problem.
Is there another way to do it?
HTML :
<div class="vertical"></div>
<div class="menu-change"></div>
<div class="horizontal">
<p>scroll</p>
</div>
CSS :
body {
overflow-x: hidden;
padding: 0;
margin: 0;
}
.scroll {
position: fixed;
bottom: 0;
left: 0;
}
.vertical {
width: 100vw;
height: 2500px;
background-image: url(https://source.unsplash.com/random);
}
.horizontal {
width: 8500px;
height: 100vh;
background-image: url(https://source.unsplash.com/random);
}
JS :
$(document).ready(function(){
var scroll_start = 0;
var startchange = $('.menu-change');
var offset = startchange.offset();
$(document).scroll(function() {
scroll_start = $(this).scrollTop();
if(scroll_start > offset.top) {
$('.horizontal').addClass('scroll');
var elem = $.jInvertScroll(['.scroll'],
{
onScroll: function(percent) {
console.log(percent);
}
});
$(window).resize(function() {
if ($(window).width() <= 0) {
elem.destroy();
}
else {
elem.reinitialize();
}
});
} else {
$('.horizontal').removeClass('scroll');
}
});
});

Creating links for page transitions

I'm writing a single page website. It has 3 'slides' like About/Music/Contact. The access to these slides is created with a dropdown menu. When you click the link in menu, the current page wrapper go visibility: hidden and through animation the following becomes visible. This works quite well, but everything happens on the root page, without changing the URL, which isn't user-friendly as if you want to share the link to the page you will always be redirected to the root.
So the question is: "How to make the url change without reloading the page (maybe through hash or smth) on the click?". Thanks in advance.
P.S. No code needed, just give me your way to make this, and I will add it into the code.
Just check with this and take it if you want this
function isElementInViewport (el) {
//special bonus for those using jQuery
if (typeof jQuery === "function" && el instanceof jQuery) {
el = el[0];
}
var rect = el.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
);
}
// click-to-scroll behavior
$("a").click(function (e) {
e.preventDefault();
var section = this.href;
var sectionClean = section.substring(section.indexOf("#"));
$("html, body").animate({
scrollTop: $(sectionClean).offset().top
}, 1000, function () {
window.location.hash = sectionClean;
});
});
// listen for the scroll event
$(document).on("scroll", function() {
//console.log("onscroll event fired...");
// check if the anchor elements are visible
$(".common").each(function (idx, el) {
if ( isElementInViewport(el) ) {
// update the URL hash
if (window.history.pushState) {
var urlHash = "#" + $(el).attr("id");
window.history.pushState(null, null, urlHash);
}
}
});
});
body {
float: left;
width: 100%;
padding-bottom: 0px;
}
.common {
width: 100%;
float: left;
height: 100vh;
display: table;
}
.allbody {
float: left;
width: 100%;
}
a {
display: inline-block;
padding: 15px;
}
header {
float: left;
width: 100%;
position: fixed;
top: 0;
left: 0;
background: #fff;
}
.common h2 {
font-size: 30px;
color: #fff;
text-align: center;
padding-top: 10%;
display: table-cell;
vertical-align: middle;
}
#firstDestination {
background: #000;
}
#secondDestination {
background: #999;
}
#thirdDestination {
background: #ccc;
}
#fourthDestination {
background: #c1c1c1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<header>
first page
<a href="#secondDestination" >second page</a>
third page
fourth page
</header>
<div class="allbody">
<div class="common" id="firstDestination" ><h2>First Page</h2></div>
<div class="common" id="secondDestination"><h2>Second Page</h2></div>
<div class="common" id="thirdDestination" ><h2>Third Page</h2></div>
<div class="common" id="fourthDestination" ><h2>Fourth Page</h2></div>
</div>

Categories

Resources