How to add a padding top to smooth scroll - javascript

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.

Related

Want JavaScript script to run when the Div is in the viewport

I want to run a JS script when a particular div comes into the viewport/is visible.
The div will always be visible, but when the user scrolls it in to view.
I have created a JSFiddle with the example:
Example http://jsfiddle.net/sv8boe9u/21/
JS
consoleText(['HELLO,', 'HERE IS A BIT ABOUT ME,', 'ENJOY!'], 'text', ['#333', '#333', '#333']);
function consoleText(words, id, colors) {
"use strict";
if (colors === undefined) {
colors = ['#fff'];
}
var visible = true;
var con = document.getElementById('console');
var letterCount = 1;
var x = 1;
var waiting = false;
var target = document.getElementById(id);
target.setAttribute('style', 'color:' + colors[0]);
window.setInterval(function() {
if (letterCount === 0 && waiting === false) {
waiting = true;
target.innerHTML = words[0].substring(0, letterCount);
window.setTimeout(function() {
var usedColor = colors.shift();
colors.push(usedColor);
var usedWord = words.shift();
words.push(usedWord);
x = 1;
target.setAttribute('style', 'color:' + colors[0]);
letterCount += x;
waiting = false;
}, 1000);
} else if (letterCount === words[0].length + 1 && waiting === false) {
waiting = true;
window.setTimeout(function() {
x = -1;
letterCount += x;
waiting = false;
}, 1000);
} else if (waiting === false) {
target.innerHTML = words[0].substring(0, letterCount);
letterCount += x;
}
}, 120);
window.setInterval(function() {
if (visible === true) {
con.className = 'console-underscore hidden';
visible = false;
} else {
con.className = 'console-underscore';
visible = true;
}
}, 400);
}
To clarify, I want it to start at 'Hello' when it is actually in viewport. Any ideas?
Thanks.
Using the jQuery scroll() and scrollTop() functions you can specify a height in px that triggers another function when reached such as:
$(window).scroll(function () {
if ($(this).scrollTop() >= 50) { // If page is scrolled more than 50px
doSomething(); // call this function
}
});
jQuery Scroll and Scroll Top
you can use the scroll function ..like create a function that runs until wen you reach that element u are targeting.. then call the alert('hello');
window.addEventListener('scroll', (e) => {
console.log(window.scrollY)
if (window.scrollY == 705) {
alert('got ya')
// do your stuff here boss
}
})
you should make sure to find that scroll position wen yo element comes into view and then put it wr 705 is.. hope this helps ya

Horizontal scrolling of a div using mouse and touch

Let's say I have a white-space: nowrap; div with overflow: hidden;. Its content is, of course, much longer than the div is, and needs to be scrolled to get revealed.
I was using this library, but it does not work for mobile devices with touch input. Do you know any alternative or ways to implement this feature?
Finally, my wish is fullfilled. Here I modified dragscroll.js library to enable touch support.
/* Modified dragscroll.js by Undust4able */
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define(['exports'], factory);
} else if (typeof exports !== 'undefined') {
factory(exports);
} else {
factory((root.dragscroll = {}));
}
}(this, function (exports) {
var _window = window;
var _document = document;
var mousemove = 'mousemove';
var mouseup = 'mouseup';
var mousedown = 'mousedown';
var touchmove = 'touchmove';
var touchup = 'touchend';
var touchdown = 'touchstart';
var EventListener = 'EventListener';
var addEventListener = 'add'+EventListener;
var removeEventListener = 'remove'+EventListener;
var dragged = [];
var reset = function(i, el) {
for (i = 0; i < dragged.length;) {
el = dragged[i++];
el = el.container || el;
el[removeEventListener](mousedown, el.md, 0);
_window[removeEventListener](mouseup, el.mu, 0);
_window[removeEventListener](mousemove, el.mm, 0);
el[removeEventListener](touchdown, el.td, 0);
_window[removeEventListener](touchup, el.tu, 0);
_window[removeEventListener](touchmove, el.tm, 0);
}
// cloning into array since HTMLCollection is updated dynamically
dragged = [].slice.call(_document.getElementsByClassName('dragscroll'));
for (i = 0; i < dragged.length;) {
(function(el, lastClientX, lastClientY, pushed, scroller, cont){
(cont = el.container || el)[addEventListener](
mousedown,
cont.md = function(e) {
if (!el.hasAttribute('nochilddrag') ||
_document.elementFromPoint(
e.pageX, e.pageY
) == cont
) {
pushed = 1;
lastClientX = e.clientX;
lastClientY = e.clientY;
e.preventDefault();
}
}, 0
);
(cont = el.container || el)[addEventListener](
touchdown,
cont.td = function(e) {
if (!el.hasAttribute('nochilddrag') ||
_document.elementFromPoint(
e.pageX, e.pageY
) == cont
) {
pushed = 1;
e.preventDefault();
e = e.targetTouches[0];
lastClientX = e.clientX;
lastClientY = e.clientY;
}
}, 0
);
_window[addEventListener](
mouseup, cont.mu = function() {pushed = 0;}, 0
);
_window[addEventListener](
touchup, cont.tu = function() {pushed = 0;}, 0
);
_window[addEventListener](
mousemove,
cont.mm = function(e) {
if (pushed) {
(scroller = el.scroller||el).scrollLeft -=
(- lastClientX + (lastClientX=e.clientX));
scroller.scrollTop -=
(- lastClientY + (lastClientY=e.clientY));
}
}, 0
);
_window[addEventListener](
touchmove,
cont.tm = function(e) {
if (pushed) {
e = e.targetTouches[0];
(scroller = el.scroller||el).scrollLeft -=
(- lastClientX + (lastClientX=e.clientX));
scroller.scrollTop -=
(- lastClientY + (lastClientY=e.clientY));
}
}, 0
);
})(dragged[i++]);
}
}
if (_document.readyState == 'complete') {
reset();
} else {
_window[addEventListener]('load', reset, 0);
}
exports.reset = reset;
}));
Make a container div with overflow-y: hidden;overflow-x: scroll; and set it to whatever pre-determined height you want.
Then have your inner div that will house the content set to position:absolute; and set its width to whatever size you need the accommodate your content.
The content will scroll with the mouse and by touch.
Sounds kinda like you're going for a netflix style side scroller - check out this codepen I've done up that shows what I was just talking about.
http://codepen.io/hoonin_hooligan/pen/aZBxRG

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()]);
}

Easy Smooth Scroll Plugin: How do I offset scroll?

I am using the Easy Smooth Scroll Plugin for Wordpress.
Below is the .js file that the plugin uses:
var ss = {
fixAllLinks: function() {
var allLinks = document.getElementsByTagName('a');
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)) {
ss.addEvent(lnk, 'click', ss.smoothScroll);
}
}
},
smoothScroll: function(e) {
if (window.event) {
target = window.event.srcElement;
} else if (e) {
target = e.target;
} else return;
if (target.nodeName.toLowerCase() != 'a') {
target = target.parentNode;
}
if (target.nodeName.toLowerCase() != 'a') return;
anchor = target.hash.substr(1);
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 (!destinationLink) return true;
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;
}
clearInterval(ss.INTERVAL);
cypos = ss.getCurrentYPos();
ss_stepsize = parseInt((desty - cypos) / ss.STEPS);
ss.INTERVAL = setInterval('ss.scrollWindow(' + ss_stepsize + ',' + desty + ',"' + anchor + '")', 10);
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)) {
window.scrollTo(0, dest);
clearInterval(ss.INTERVAL);
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) {
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);
The live page is here: http://iamjoepro.com/album/promaha/
I have the smooth scroll scrolling to an anchor, but I would like to offset it by the height of my fixed header (120px)
I am no javascript expert, I'm hoping this is easy for someone, but I can't decipher where to add the offset in my .js file?
I had a similar issue and found that the following solution worked for me.
Change the line:
var desty = destinationLink.offsetTop;
to read:
var desty = destinationLink.offsetTop - 120;
(where '120' is the height in pixels of your fixed header)
Then, remove the line:
location.hash = anchor;
(otherwise, the page will scroll to your 120px offset but then return back to the location of the anchor)
Hope this helps!

Prevent Javascript from executing in Safari

The following smooth scrolling script messes up my navigation in Safari (anchor tags don't work anymore). I'm a Javascript newbie, could anyone tell me how to detect Safari in this script and prevent it from executing when it detects Safari? Many thanks!
// JavaScript Document
$(document).ready(function() {
function filterPath(string) {
return string
.replace(/^\//,'')
.replace(/(index|default).[a-zA-Z]{3,4}$/,'')
.replace(/\/$/,'');
}
var locationPath = filterPath(location.pathname);
var scrollElem = scrollableElement('html', 'body');
$('a[href*=#]').each(function() {
var thisPath = filterPath(this.pathname) || locationPath;
if ( locationPath == thisPath
&& (location.hostname == this.hostname || !this.hostname)
&& this.hash.replace(/#/,'') ) {
var $target = $(this.hash), target = this.hash;
if (target) {
var targetOffset = $target.offset().top;
$(this).click(function(event) {
event.preventDefault();
$(scrollElem).animate({scrollTop: targetOffset}, 1300, function() { // scroll speed
location.hash = target;
});
});
}
}
});
// use the first element that is "scrollable"
function scrollableElement(els) {
for (var i = 0, argLength = arguments.length; i <argLength; i++) {
var el = arguments[i],
$scrollElement = $(el);
if ($scrollElement.scrollTop()> 0) {
return el;
} else {
$scrollElement.scrollTop(1);
var isScrollable = $scrollElement.scrollTop()> 0;
$scrollElement.scrollTop(0);
if (isScrollable) {
return el;
}
}
}
return [];
}
});
var isSafari = navigator.userAgent.indexOf("Safari") > -1 && navigator.userAgent.indexOf("Chrome") == -1;
if(!isSafari){
// do your magic
}
Refer: http://api.jquery.com/jQuery.browser/, to detect browser and execute script only if it is not safari
Perhaps this:
$(document).ready(function()
{
if (navigator.appVersion.match(/WebKit/) && !navigator.vendor.match(/Google/))
{
return;
}
//rest of your code
});
if you have any code outside the $(document).ready callback, you could kill the script by throwing an error, by writing this at the top of your script(s):
if (navigator.appVersion.match(/WebKit/) && !navigator.vendor.match(/Google/))
{
throw new Error('Safari not supported');
}

Categories

Resources