How when I scroll highest and then remove class - javascript

I have a question about when I scroll highest I want to remove the class that have position fixed because the position fixed will hide my div right, so I need remove it and dont hide my div when I scroll highest.
May I know can only edit the javascript code to solved it? ty
Here is my codepen link
https://codepen.io/WeiKang-Ng/pen/bGxGQwx
Here is js code
(function(){
var doc = document.documentElement;
var w = window;
/*
define four variables: curScroll, prevScroll, curDirection, prevDirection
*/
var curScroll;
var prevScroll = w.scrollY || doc.scrollTop;
var curDirection = 0;
var prevDirection = 0;
var header = document.getElementById('site-header');
var toggled;
var threshold = 100;
var checkScroll = function() {
curScroll = w.scrollY || doc.scrollTop;
if(curScroll > prevScroll) {
// scrolled down
curDirection = 2;
}
else {
//scrolled up
curDirection = 1;
}
if(curDirection !== prevDirection) {
toggled = toggleHeader();
}
prevScroll = curScroll;
if(toggled) {
prevDirection = curDirection;
}
};
var toggleHeader = function() {
toggled = true;
if (curDirection === 2 && curScroll > threshold) {
header.classList.add("nav-on-scroll");
header.classList.remove("show-nav-on-scroll");
} else if (curDirection === 1 && curScroll > threshold) {
header.classList.add("show-nav-on-scroll");
} else {
toggled = false;
}
return toggled
};
window.addEventListener('scroll', checkScroll);
})();

you need to add 2 lines to remove class from the header.
1st line removes the class if the user is scrolling up and has not yet reached the threshold.
2nd line removes the class if the user is not scrolling or has scrolled past the threshold.
modify the toggleHeader function as follow
var toggleHeader = function() {
toggled = true;
if (curDirection === 2 && curScroll > threshold) {
header.classList.add("nav-on-scroll");
header.classList.remove("show-nav-on-scroll");
} else if (curDirection === 1 && curScroll > threshold) {
header.classList.add("show-nav-on-scroll");
header.classList.remove("nav-on-scroll");
} else {
toggled = false;
header.classList.remove("nav-on-scroll");
}
return toggled;
};

Related

header hide on scroll - delay on scroll up

I want to add a delay to this header when the user scrolls 200px up: https://codepen.io/iabhinavr/pen/BaKxvRx
If see the codepen, right now it only delays on scrolls down.
This is what I have tried:
// menu hide on scroll
(function(){
var doc = document.documentElement;
var w = window;
var curScroll;
var prevScroll = w.scrollY || doc.scrollTop;
var curDirection = 0;
var prevDirection = 0;
var header = document.getElementById('site-header');
var toggled;
var threshold = 350;
var thresholdScrollUp = 200;
var checkScroll = function() {
curScroll = w.scrollY || doc.scrollTop;
curScrollBottom = w.scrollY || doc.scrollTop;
if(curScroll > prevScroll) {
// scrolled down
curDirection = 2;
}
else {
//scrolled up
curDirection = 1;
}
if(curDirection !== prevDirection) {
toggled = toggleHeader();
}
prevScroll = curScroll;
if(toggled) {
prevDirection = curDirection;
}
};
var toggleHeader = function() {
toggled = true;
if(curDirection === 2 && curScroll > threshold) {
header.classList.add('hide');
jQuery('#site-header-sticky-wrapper').addClass('hide');
}
else if (curDirection === 1 && curScrollBottom > thresholdScrollUp) {
jQuery('#site-header-sticky-wrapper').removeClass('hide');
header.classList.remove('hide');
}
else {
toggled = false;
}
return toggled;
};
window.addEventListener('scroll', checkScroll);
})();
I added:
var thresholdScrollUp = 200;
and changed:
else if (curDirection === 1)
to:
else if (curDirection === 1 && curScrollBottom > thresholdScrollUp)
Any help would be appreciated
Your provided code pen code work differently. Checkout this one
(function(){
var doc = document.documentElement;
var w = window;
var curScroll;
var prevScroll = w.scrollY || doc.scrollTop;
var curDirection = 0;
var prevDirection = 0;
var lastY = 0;
var header = document.getElementById('site-header');
var toggled;
var threshold = 200;
var checkScroll = function() {
curScroll = w.scrollY || doc.scrollTop;
if(curScroll > prevScroll) {
// scrolled down
curDirection = 2;
}
else {
//scrolled up
curDirection = 1;
}
if(curDirection !== prevDirection) {
toggled = toggleHeader();
} else {
lastY=curScroll
}
prevScroll = curScroll;
if(toggled) {
prevDirection = curDirection;
}
};
var toggleHeader = function() {
toggled = true;
if(curDirection === 2 && (curScroll-lastY) > threshold) {
lastY=curScroll
header.classList.add('hide');
}
else if (curDirection === 1 && (lastY-curScroll) > threshold) {
lastY=curScroll
header.classList.remove('hide');
}
else {
toggled = false;
}
return toggled;
};
window.addEventListener('scroll', checkScroll);
})();

How to add a padding top to smooth scroll

I have implemented a javascript smooth scroll in a one page site and works perfectly. However, because I have a fixed nav at the top of the page, when the page scrolls to the anchor, the top of the page disappears behind the nav. How can I offset the scroll of 90px?
Here is the code:
var ss = {
fixAllLinks: function() {
// Get a list of all links in the page
var allLinks = document.getElementsByTagName('a');
// Walk through the list
for (var i=0;i<allLinks.length;i++) {
var lnk = allLinks[i];
if ((lnk.href && lnk.href.indexOf('#') != -1) &&
( (lnk.pathname == location.pathname) ||
('/'+lnk.pathname == location.pathname) ) &&
(lnk.search == location.search)) {
// If the link is internal to the page (begins in #)
// then attach the smoothScroll function as an onclick
// event handler
ss.addEvent(lnk,'click',ss.smoothScroll);
}
}
},
smoothScroll: function(e) {
// This is an event handler; get the clicked on element,
// in a cross-browser fashion
if (window.event) {
target = window.event.srcElement;
} else if (e) {
target = e.target;
} else return;
// Make sure that the target is an element, not a text node
// within an element
if (target.nodeName.toLowerCase() != 'a') {
target = target.parentNode;
}
// Paranoia; check this is an A tag
if (target.nodeName.toLowerCase() != 'a') return;
// Find the <a name> tag corresponding to this href
// First strip off the hash (first character)
anchor = target.hash.substr(1);
// Now loop all A tags until we find one with that name
var allLinks = document.getElementsByTagName('a');
var destinationLink = null;
for (var i=0;i<allLinks.length;i++) {
var lnk = allLinks[i];
if (lnk.name && (lnk.name == anchor)) {
destinationLink = lnk;
break;
}
}
if (!destinationLink) destinationLink = document.getElementById(anchor);
// If we didn't find a destination, give up and let the browser do
// its thing
if (!destinationLink) return true;
// Find the destination's position
var destx = destinationLink.offsetLeft;
var desty = destinationLink.offsetTop;
var thisNode = destinationLink;
while (thisNode.offsetParent &&
(thisNode.offsetParent != document.body)) {
thisNode = thisNode.offsetParent;
destx += thisNode.offsetLeft;
desty += thisNode.offsetTop;
}
// Stop any current scrolling
clearInterval(ss.INTERVAL);
cypos = ss.getCurrentYPos();
ss_stepsize = parseInt((desty-cypos)/ss.STEPS);
ss.INTERVAL =
setInterval('ss.scrollWindow('+ss_stepsize+','+desty+',"'+anchor+'")',20);
// And stop the actual click happening
if (window.event) {
window.event.cancelBubble = true;
window.event.returnValue = false;
}
if (e && e.preventDefault && e.stopPropagation) {
e.preventDefault();
e.stopPropagation();
}
},
scrollWindow: function(scramount,dest,anchor) {
wascypos = ss.getCurrentYPos();
isAbove = (wascypos < dest);
window.scrollTo(0,wascypos + scramount);
iscypos = ss.getCurrentYPos();
isAboveNow = (iscypos < dest);
if ((isAbove != isAboveNow) || (wascypos == iscypos)) {
// if we've just scrolled past the destination, or
// we haven't moved from the last scroll (i.e., we're at the
// bottom of the page) then scroll exactly to the link
window.scrollTo(0,dest);
// cancel the repeating timer
clearInterval(ss.INTERVAL);
// and jump to the link directly so the URL's right
location.hash = anchor;
}
},
getCurrentYPos: function() {
if (document.body && document.body.scrollTop)
return document.body.scrollTop;
if (document.documentElement && document.documentElement.scrollTop)
return document.documentElement.scrollTop;
if (window.pageYOffset)
return window.pageYOffset;
return 0;
},
addEvent: function(elm, evType, fn, useCapture) {
// addEvent and removeEvent
// cross-browser event handling for IE5+, NS6 and Mozilla
// By Scott Andrew
if (elm.addEventListener){
elm.addEventListener(evType, fn, useCapture);
return true;
} else if (elm.attachEvent){
var r = elm.attachEvent("on"+evType, fn);
return r;
} else {
alert("Handler could not be removed");
}
}
}
ss.STEPS = 25;
ss.addEvent(window,"load",ss.fixAllLinks);
Thanks in advance for your help!
You can do a calculation when setting the destination coordinates:
// Find the destination's position
var destx = destinationLink.offsetLeft;
var desty = destinationLink.offsetTop;
var thisNode = destinationLink;
while (thisNode.offsetParent &&
(thisNode.offsetParent != document.body)) {
thisNode = thisNode.offsetParent;
destx += thisNode.offsetLeft;
desty += thisNode.offsetTop;
}
//subtract nav from offset position
desty = desty - 90;
if(desty < 0){ desty = 0; }
That being said, using a static number is dangerous business. Might make more sense to calculate minus the header's actual height instead.
Simply make changes in the CSS:
html{
scroll-behavior: smooth;
scroll-padding-top: 50px;
}
This will handle your fixed header issue.

jQuery does not adjust scroll position

Basically, I want to have certain points on my website, that act like "magnets". If you are near one of these, the window should scroll to the top, similar to this jQuery plug-in : http://benoit.pointet.info/stuff/jquery-scrollsnap-plugin/
The problem is, that the window does not scroll, even though the page is in range of a "magnet".
here is the jQuery:
$(document).ready( function() {
var magnets = [];
var range = 200;
var active = true;
$('.container').each(function(i,obj) {
magnets.push($(this).offset().top);
});
console.log(magnets);
var attract = function(where,time){
$('html, body').animate({
scrollTop: where
}, time);
active = false;
};
//checks the range of a magnet
var magnetic = function(what){
var top = $(window).scrollTop();
var min = top - range;
var max = top + range;
if( (min <= what) && (max >= what) ){
return true;
} else{
return false;
}
}
//returns, wether you are in range of a magnet from your magnets array or not
var inRange = function(){
var magnet = -1;
for(var i=0; i<magnets.length; i++){
if( magnetic(magnets[i]) == true){
magnet = i;
}
}
return magnet;
}
$(window).scroll(function() {
$('.counter').html("");
$('.counter').append("<p>"+inRange()+"</p>");
if(active == true && inRange != -1){
attract(magnets[inRange()]);
}
else if(active == false && inRange() == -1){
active = true;
}
else if(active == true && inRange() == -1){
console.log("fuck");
}
});
});
alternative codepen link: http://codepen.io/NiclasvanEyk/pen/jEMrZr
There is a mistake in your code:
if(active == true && inRange != -1){
attract(magnets[inRange()]);
}
Should be
if(active == true && inRange() != -1){
attract(magnets[inRange()]);
}

Mouswheel with one page navi - scroll only at the end of section

I had onepageNav script to scrollTo pages. Pages it's not full height of window than i had problem with addition mousewhell.
I had code:
$('body').mousewheel(function(event, delta) {
if (flag) { return false; }
$current = $('section.current');
if (delta > 0) {
$prev = $current.prev();
if ($prev.length) {
flag = true;
$('body').scrollTo($prev, 1000, {
onAfter : function(){
flag = false;
}
});
$current.removeClass('current');
$prev.addClass('current');
}
} else {
$next = $current.next();
if ($next.length) {
flag = true;
$('body').scrollTo($next, 1000, {
onAfter : function(){
flag = false;
}
});
$current.removeClass('current');
$next.addClass('current');
}
}
event.preventDefault();
});
It's script for mousewheel. It's work but not exacly what i want.
If i had section #2 bigger than window than it's go automaticaly after scroll to next section.
I i had section #3 last, bigget than windows and i scroll down than scrolling stop working.
Someone had idea how to resolve that?
If I understand you correctly you can use the following code:
HTML:
<section id='s1'></section>
<section id='s2'></section>
<section id='s3'></section>
<section id='s4'></section>
JS:
function elementInViewport2(el) {
var top = el.offsetTop;
var left = el.offsetLeft;
var width = el.offsetWidth;
var height = el.offsetHeight;
while(el.offsetParent) {
el = el.offsetParent;
top += el.offsetTop;
left += el.offsetLeft;
}
return (
top < (window.pageYOffset + window.innerHeight) &&
left < (window.pageXOffset + window.innerWidth) &&
(top + height) > window.pageYOffset &&
(left + width) > window.pageXOffset
);
};
var current = $('section').first();
current.addClass('current');
var flag;
$(window).scroll(function(event, delta) {
if (flag) { return false; }
var $body = $('body'),
$window = $(window),
newScroll = $body.scrollTop();
if (!elementInViewport2(current[0])) {
current.removeClass('current');
current[0] = null;
}
var newSection = $('section:not(.current)').filter(function(i, el) {
return elementInViewport2(el);
}).first();
if (newSection[0] && current[0] != newSection[0]) {
current.removeClass('current');
current = newSection;
newSection.addClass('current');
flag = true;
$body.animate({scrollTop: newSection.offset().top}, function() {
flag = false;
});
event.preventDefault();
}
});
Demo

Simulating shuffle in js

All,
I have three cards which can be shuffled by the user, upon hover, the target card pops to the top, the last card on top should sit in the second position. While with the code below, I can have this effect in one direction (left to right), I am struggling to come up with logic & code for getting the effect to work in both directions without having to write multiple scenarios in js (which doesnt sound like very good logic).
Hopefully the demo will do a better explanation.
Code:
$(".cBBTemplates").on (
{
hover: function (e)
{
var aBBTemplates = document.getElementsByClassName ("cBBTemplates");
var i = 2;
while (i < aBBTemplates.length && i >= 0)
{
var eCurVar = aBBTemplates[i];
if (eCurVar === e.target)
{
eCurVar.style.zIndex = 3;
} else if (eCurVar.style.zIndex === 3) {
console.log (eCurVar);
eCurVar.style.zIndex = 3-1;
} else
{
eCurVar.style.zIndex = i;
}
i--;
}
}
});
Try this:
$(function(){
var current = 2;
$(".cBBTemplates").on (
{
hover: function ()
{
var target = this,
newCurrent, templates = $(".cBBTemplates");
templates.each(
function(idx){
if(this === target){
newCurrent = idx;
}
});
if(newCurrent === current){return;}
templates.each(function(index){
var zIndex = 0;
if(this === target) {
zIndex = 2;
}
else if (index == current) {
zIndex = 1;
}
$(this).css('zIndex', zIndex);
});
current = newCurrent;
}
});
});

Categories

Resources