Scroll to pure javascript not working - javascript

Yes I am avoiding a 3rd party lib on purpose, very small app on mobile device and don't want to pull anything.
I am trying to scroll to elements on a page using this scrollTo function:
function scrollTo(element, to, duration) {
if (duration <= 0) return;
var difference = to - element.scrollTop;
var perTick = difference / duration * 10;
setTimeout(function() {
element.scrollTop = element.scrollTop + perTick;
if (element.scrollTop === to) return;
scrollTo(element, to, duration - 10);
}, 10);
}
I grab a list of span tags that I want to use as my scroll points each time the user clicks a next button:
var index = null;
function next() {
var list = document.querySelectorAll("span");
var element = null;
if (index == null) {
index = -1;
element = document.body;
} else {
element = list[index];
}
index++;
if (index >= list.length) {
return;
}
var to = list[index];
scrollTo(element, to.offsetTop, 250);
}
The first next click properly scrolls to the first element. However the next click does not scroll. I debugged into the scrollTo method and it seems the element.scrollTop variable is not changing each time it is assigned. Any ideas?

You musst change the element.scrollTop of the element you want to scroll on, in this case document.body. You are only doing this in the first call. After that you´re always scrolling on the list item which is your target (what has no effect, since it has no overflow).
You should call your scrollTop like this:
scrollTo(document.body, to.offsetTop, 250);
Maybe you should also take a look at
window.scrollTo()
https://developer.mozilla.org/en/docs/Web/API/Window/scrollTo

I was not able to replicate your exact issue, but what I did find was that I was not able to get to the last span with the way your code was written. To get around that, I rewrote a few things. It may fix the issue for you.
function next() {
var list = document.querySelectorAll("span");
var element = null;
if (index == null) {
index = -1;
element = document.body;
} else {
element = list[index];
}
if (index >= list.length) {
return;
}
if(index >= 0)
{
var to = list[index];
scrollTo(element, to.offsetTop, 250);
}
index++;
}
Essentially, you were trying to increment your index too soon causing it to never process the last span.

Related

Creating a simple "smooth scroll" (with javascript vanilla)

I have been trying to make a simple "smoothscroll" function using location.href that triggers on the mousewheel. The main problem is that the EventListener(wheel..) gets a bunch of inputs over the span of ca. 0,9 seconds which keeps triggering the function. "I only want the function to run once".
In the code below I have tried to remove the eventlistener as soon as the function runs, which actually kinda work, the problem is that I want it to be added again, hence the timed function at the bottom. This also kinda work but I dont want to wait a full second to be able to scroll and if I set it to anything lover the function will run multiple times.
I've also tried doing it with conditions "the commented out true or false variables" which works perfectly aslong as you are only scrolling up and down but you cant scroll twice or down twice.
window.addEventListener('wheel', scrolltest, true);
function scrolltest(event) {
window.removeEventListener('wheel', scrolltest, true);
i = event.deltaY;
console.log(i);
if (webstate == 0) {
if (i < 0 && !upexecuted) {
// upexecuted = true;
location.href = "#forside";
// downexecuted = false;
} else if (i > 0 && !downexecuted) {
// downexecuted = true;
location.href = "#underside";
// upexecuted = false;
}
}
setTimeout(function(){ window.addEventListener('wheel', scrolltest, true); }, 1000);
}
I had hoped there was a way to stop the wheel from constantly produce inputs over atleast 0.9 seconds.
"note: don't know if it can help in some way but when the browser is not clicked (the active window) the wheel will registre only one value a nice 100 for down and -100 for up"
What you're trying to do is called "debouncing" or "throttling". (Those aren't exactly the same thing, but you can look up the difference in case it's going to matter to you.) Functions for this are built into libraries like lodash, but if using a library like that is too non-vanilla for what you have in mind, you can always define your own debounce function: https://www.geeksforgeeks.org/debouncing-in-javascript/
You might also want to look into requestanimationframe.
a different approach
okey after fiddeling with this for just about 2 days i got fustrated and started over. no matter what i did the browsers integrated "glide-scroll" was messing up the event trigger. anyway i decided to animate the scrolling myself and honestly it works better than i had imagined: here is my code if anyone want to do this:
var body = document.getElementsByTagName("BODY")[0];
var p1 = document.getElementById('page1');
var p2 = document.getElementById('page2');
var p3 = document.getElementById('page3');
var p4 = document.getElementById('page4');
var p5 = document.getElementById('page5');
var whatpage = 1;
var snap = 50;
var i = 0;
// this part is really just to read what "page" you are on if you update the site. if you add more pages you should remember to add it here too.
window.onload = setcurrentpage;
function setcurrentpage() {
if (window.pageYOffset == p1.offsetTop) {
whatpage = 1;
} else if (window.pageYOffset == p2.offsetTop) {
whatpage = 2;
} else if (window.pageYOffset == p3.offsetTop) {
whatpage = 3;
} else if (window.pageYOffset == p4.offsetTop) {
whatpage = 4;
} else if (window.pageYOffset == p5.offsetTop) {
whatpage = 5;
}
}
// this code is designet to automaticly work with any "id" you have aslong as you give it a variable called p"number" fx p10 as seen above.
function smoothscroll() {
var whatpagenext = whatpage+1;
var whatpageprev = whatpage-1;
var currentpage = window['p'+whatpage];
var nextpage = window['p'+whatpagenext];
var prevpage = window['p'+whatpageprev];
console.log(currentpage);
if (window.pageYOffset > currentpage.offsetTop + snap && window.pageYOffset < nextpage.offsetTop - snap){
body.style.overflowY = "hidden";
i++
window.scrollTo(0, window.pageYOffset+i);
if (window.pageYOffset <= nextpage.offsetTop + snap && window.pageYOffset >= nextpage.offsetTop - snap) {
i=0;
window.scrollTo(0, nextpage.offsetTop);
whatpage += 1;
body.style.overflowY = "initial";
}
} else if (window.pageYOffset < currentpage.offsetTop - snap && window.pageYOffset > prevpage.offsetTop + snap){
body.style.overflowY = "hidden";
i--
window.scrollTo(0, window.pageYOffset+i);
if (window.pageYOffset >= prevpage.offsetTop - snap && window.pageYOffset <= prevpage.offsetTop + snap) {
i=0;
window.scrollTo(0, prevpage.offsetTop);
whatpage -= 1;
body.style.overflowY = "initial";
}
}
}
to remove the scrollbar completely just add this to your stylesheet:
::-webkit-scrollbar {
width: 0px;
background: transparent;
}

Nonconcurrent async recursion

My end goal is to mitigate as much lag (window freezing/stuttering) as possible, giving the client a responsive window from page load.
My program is a Chrome extension, and part of it needs to search through a reddit submission, including all comments for certain words and then do some stuff with them. After this answer, I converted my code to use setInterval for the recursive search. Unforutnately, this runs concurrently, so even though each branch in the comment tree is delayed from its parent, the overall search overlaps each other, negating any benefit in the delay.
I have a solution, but I don't know how to implement it.
The solution would be to have a callback when a branch runs out that goes to the nearest parent fork. This in effect would traverse the comment tree linearly and would allow the setInterval (or probably setTimeout would be more appropriate) to have a noticeable affect.
The code that would need to be changed is:
function highlightComments(){
var elems = $(".content .usertext-body > .md");
var index = 0;
var total = elems.length;
console.log("comments started");
var intId = setInterval(function(){
highlightField(elems.get(index));
index++;
if(index == total){
clearInterval(intId);
addOnClick();
console.log("comments finished");
}
}, 25);
}
and highlightField is:
function highlightField(node) {
var found = $(node).attr("data-ggdc-found") === "1";
var contents = $.makeArray($(node).contents());
var index = 0;
var total = contents.length;
if (total == 0){
return;
}
var intId = setInterval(function() {
if (contents[index].nodeType === 3) { // Text
if (!found){
//Mods
var content = contents[index].nodeValue.replace(new RegExp(data.mods.regex, "gi"), data.mods.replacement);
//Creators
content = content.replace(new RegExp(data.creators.regex, "gi"), data.creators.replacement);
//Blacklist
for (var key in data.blacklist.regex){
if(data.blacklist.regex.hasOwnProperty(key)){
content = content.replace(new RegExp(data.blacklist.regex[key], "gi"), data.blacklist.replacement[key]);
}
}
if (content !== contents[index].nodeValue) {
$(contents[index]).replaceWith(content);
}
}
} else if (contents[index].nodeType === 1) { // Element
highlightField(contents[index]);
}
index++;
if(index == total){
clearInterval(intId);
}
}, 25);
}

Javascript - How do I improve performance when animating integers?

On the site I'm working on, we collect data from a datasource and present these in their own design element, in the form of an SVG. The SVG files are renamed to .php in order to insert the dynamic data from the datasource.
Then, I'm using inview javascript to initialize a function that animates the data from the source, from 0 to their actual value. However, I notice this gets kinda heavy on the browser, when there are a lot of elements that are running the animate function.
Is there perhaps a smarter way of doing this? I haven't really dug that much into it, because it's not that bad. I just happened to notice the lag when scrolling through the area being repainted.
Here's my js code:
$('.inview article').bind('inview', function(event, isInView, visiblePartX, visiblePartY) {
if (isInView) {
// element is now visible in the viewport
if (visiblePartY == 'top' || visiblePartY == 'both' || visiblePartY == 'bottom') {
var $this = $(this);
var element = $($this);
$this.addClass('active');
reinitializeText(element);
$this.unbind('inview');
// top part of element is visible
} else if (visiblePartY == 'bottom') {
} else {
}
} else {
}
});
function reinitializeText(element) {
var svg = element.find('svg');
var children = svg.children('.infographics_svg-text');
// If there is no class in svg file, search other elements for the class
if (children.length == 0) {
var children = element.find('.infographics_svg-text');
}
children.each(function (){
var step = this.textContent/100;
var round = false;
if (this.textContent.indexOf('.') !=-1) {
round = true;
}
animateText(this, 0, step, round);
});
}
function animateText(element, current, step, round) {
if (current > 100) return;
var num = current++ *step;
if (round) {
num = Math.round((num)*100)/100
} else {
num = Math.round(num);
}
element.textContent = num;
setTimeout(function() {
animateText(element, current, step, round);
}, 10);
}
Edit: Because of the difference in data values received from the source (low numbers to huge numbers), The speed of the animation is increased so it doesn't go on forever

animate when window.location.hash changes

so i'm trying to get a site gallery-like, i have the articles that spreads all across the page and my idea is that when i get an action from the user the site jumps to the next article.
I have done a lot of work so far and it's a couple of days i'm behind javascript, i'm using jquery and the code is this
$('body').ready(function () {
var tpScroll = 0;
var SelArticles = $('#content').find('.bgjs');
var NumArticles = SelArticles.length;
window.location.hash = SelArticles.first().attr('id');
$(window).bind('mousewheel', function (event, delta, deltaX, deltaY) {
event.preventDefault();
console.log(delta, deltaX, deltaY);
console.log(tpScroll);
if (delta < 0) {
if (tpScroll >= (NumArticles - 1)) {
tpScroll = 0;
} else {
tpScroll = tpScroll + 1;
}
var pgid = SelArticles.eq(tpScroll).attr('id');
window.location.hash = pgid;
} else {
if (tpScroll <= 0) {
tpScroll = (NumArticles - 1);
} else {
tpScroll = tpScroll - 1;
}
var pgid = SelArticles.eq(tpScroll).attr('id');
window.location.hash = pgid;
}
});
});
i managed to handle the mousewheel event to make the hash change, but i want to prevent the default scroll to the content adding a smooth animation.
I'm not a monster in javascript (neither jquery) as you can see , but it's kind of working, i don't even know if it's possible to prevend this behavior, or to work around it... any suggestion?
I just completely changed approach, i used wiselinks to handle history apis, turned out to be a great choice

Javascript "For" Loop not working?

I have a Javascript file that I am using to try to animate a dropdown menu. I have the "Toggle" function in that file set to run when I click on a certain div. Here's the script I'm using:
var up = true;
function Toggle(x)
{
if (up)
{
for (var i = x.offsetTop; i <= 0; i++)
{
x.style.top = i;
if (i == 0)
{
up = false;
}
}
}
else if (up == false)
{
for (var i = x.offsetTop; i >= -50; i--)
{
x.style.top = i;
if (i == -50)
{
up = true;
}
}
}
}
In the HTML div I want to animate, I have the "onclick" property set to "onclick=Toggle(this)". The first for loop works as it should (it sets the div's top offset to 0). However, the second for loop doesn't set the offsetTop. I know that the for loop is activating because I've tested it and it gives me every integer between 0 and -50. Why isn't it setting the offset position?
1) You must specify a unit to the top ie: x.style.top = i +"px"
2) Your function won't animate instead of you use a setInterval or a setTimeout
Like you asked, an example. I wouldn't do it like this for one of my project, but i kept your function to make you more familiar with the code.
I Used setTimeout instead of setInterval because setInterval must be cleared when not needed and setTimeout is just launched one time :
var Toggle = (function() { // use scope to define up/down
var up = true;
return function(element) {
var top = parseInt(element.style.top, 10); // element.offsetTop ?
if ( !top ) {
top = 0;
}
if (up) {
if (element.offsetTop < 0) { // if we are not at 0 and want to get up
element.style.top = (top+1) + "px";
setTimeout(function() { Toggle(element); }, 10); // recall the function in 10 ms
} else { // we change up value
up = !up;
}
}
else {
if (element.offsetTop > -50) {
element.style.top = (top-1) + "px";
setTimeout(function() { Toggle(element); }, 10); // recall the function in 10 ms
} else {
up=!up;
}
}
}
})();
You'd have to use x.style.top = i + 'px' as top and similar css properties must define the type (px, em, %, etc.) unless they are 0, as this is 0 in any case.
But your script would actually snap the div directly to -50px, as you do not wait between those iteration steps.
I'd recommend to use a library like jQuery to use it's animate() method.
function Toggle(obj) {
$(obj).animate({
top: parseInt($(obj).css('top')) === 0 ? '-50px' : '0px'
})
}

Categories

Resources