I can't get Element.scrollIntoView() to work. I have the code below. There are two locations that it should scroll to, depending on some variable. However, it doesn't scroll to either of them. What am I doing wrong?
class Page extends Component {
scrollToMyRef = (id) => {
var ref = document.getElementById(id);
console.log("Ref1: " + ref); // returns [object HTMLElement]
console.log("Ref2: " + document.ref); // returns undefined
console.log("Id: " + id); // returns myRef
ref.scrollIntoView({
behavior: "smooth",
block: "start",
});
};
componentDidMount() {
if (this.props.location.state) {
if (this.props.location.state.origine) {
this.scrollToMyRef("myRef");
} else {
this.scrollToMyRef("myTopRef");
});
}
}
}
render() {
return (
<div
id="myTopRef"
key="pricing"
className="pricing"
>
...
</div>
<section id=myRef className="section">
...
</section>
...
)
}
After setting a time delay it worked:
scrollToMyRef = (id) => {
var ref = document.getElementById(id);
setTimeout(function () {
ref.scrollIntoView({
behavior: "smooth",
block: "start",
});
}, 100);
};
I was facing the same issue. scrollIntoView was working only if behavior was auto. Setting a delay fixed some cases but not all of them. In addition, Safari doesn't support smooth scrolling at all. I used this polyfill which works for all browsers and all cases.
You can use it in the following way:
import { scrollIntoView } from "seamless-scroll-polyfill";
scrollIntoView(element, {
behavior: "smooth",
block: "start",
},
{
duration: 250 // aprox. the duration that chrome uses,
}
);
Related
I have a chat button created by a script (zendesk chat). It generate an iframe in the page with the ID "launcher".
I'm using Nextjs and Im trying to get this element but I cannot attach a ref since I've not the code.
I am digging the web for a solution and I have tried something like this (in the footer component because it is on all pages and I am able to figure out which page I am on):
React.useLayoutEffect(() => {
function checkElExist() {
if (typeof document !== 'undefined') {
const el = document.querySelector('#launcher');
if (!isSingleVehiclePage) {
console.log('NOT VEHICLE', el);
if (el) {
el.classList.remove('inVehicle');
el.classList.add('notInVehiclePage');
}
} else {
console.log('IN VEHICLE', el);
if (el) {
el.classList.remove('notInVehiclePage');
el.classList.add('inVehicle');
}
}
}
}
window.addEventListener('load', checkElExist);
return () => window.removeEventListener('load', checkElExist);
}, [isSingleVehiclePage]);
I don't know if is the right solution. It kinda works but sometimes the element is null especially when I land on that specific page from an external link (not when I navigate the site).
Is it possibile to get this element? My goal is to add/remove a class to it according to specific pages.
Thanks
EDIT: I dont know if it is relevant, but in the html the iframe is out of my "__next" div. In the pic below, I circled the __next div, the footer div (where my useLayoutEffect code is executed) and the iframe I want to get.
SOLVED:
I use a function that runs recursively every 1000ms. If it can't find the element in 9000ms, it stops.
React.useEffect(() => {
waitForElementToDisplay(
'#launcher',
function (el: any) {
checkElExist(el);
},
1000,
9000
);
function checkElExist(el: any) {
if (!isSingleVehiclePage) {
console.log('NOT VEHICLE', el);
el.classList.remove('inVehicle');
el.classList.add('notInVehiclePage');
} else {
console.log('IN VEHICLE', el);
el.classList.remove('notInVehiclePage');
el.classList.add('inVehicle');
}
}
}, [isSingleVehiclePage]);
function waitForElementToDisplay(
selector: string,
callback: any,
checkFrequencyInMs: number,
timeoutInMs: number
) {
const startTimeInMs = Date.now();
(function loopSearch() {
if (document && document.querySelector(selector) != null) {
console.log('found');
const element = document.querySelector(selector);
callback(element);
return;
} else {
setTimeout(function () {
if (timeoutInMs && Date.now() - startTimeInMs > timeoutInMs) return;
loopSearch();
}, checkFrequencyInMs);
}
})();
}
I am using Javascript method Element.scrollIntoView()
https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView
Is there any way I can get to know when the scroll is over. Say there was an animation, or I have set {behavior: smooth}.
I am assuming scrolling is async and want to know if there is any callback like mechanism to it.
There is no scrollEnd event, but you can listen for the scroll event and check if it is still scrolling the window:
var scrollTimeout;
addEventListener('scroll', function(e) {
clearTimeout(scrollTimeout);
scrollTimeout = setTimeout(function() {
console.log('Scroll ended');
}, 100);
});
2022 Update:
The CSS specs recently included the overscroll and scrollend proposal, this proposal adds a few CSS overscroll attributes, and more importantly to us, a scrollend event.
Browsers are still working on implementing it. (It's already available in Chromium under the Web Platforms Experiments flag.)
We can feature-detect it by simply looking for
if (window.onscrollend !== undefined) {
// we have a scrollend event
}
While waiting for implementations everywhere, the remaining of this answer is still useful if you want to build a polyfill:
For this "smooth" behavior, all the specs say[said] is
When a user agent is to perform a smooth scroll of a scrolling box box to position, it must update the scroll position of box in a user-agent-defined fashion over a user-agent-defined amount of time.
(emphasis mine)
So not only is there no single event that will fire once it's completed, but we can't even assume any stabilized behavior between different browsers.
And indeed, current Firefox and Chrome already differ in their behavior:
Firefox seems to have a fixed duration set, and whatever the distance to scroll is, it will do it in this fixed duration ( ~500ms )
Chrome on the other hand will use a speed, that is, the duration of the operation will vary based on the distance to scroll, with an hard-limit of 3s.
So this already disqualifies all the timeout based solutions for this problem.
Now, one of the answers here has proposed to use an IntersectionObserver, which is not a too bad solution, but which is not too portable, and doesn't take the inline and block options into account.
So the best might actually be to check regularly if we did stop scrolling. To do this in a non-invasive way, we can start an requestAnimationFrame powered loop, so that our checks are performed only once per frame.
Here one such implementation, which will return a Promise that will get resolved once the scroll operation has finished.
Note: This code misses a way to check if the operation succeeded, since if an other scroll operation happens on the page, all current ones are cancelled, but I'll leave this as an exercise for the reader.
const buttons = [ ...document.querySelectorAll( 'button' ) ];
document.addEventListener( 'click', ({ target }) => {
// handle delegated event
target = target.closest('button');
if( !target ) { return; }
// find where to go next
const next_index = (buttons.indexOf(target) + 1) % buttons.length;
const next_btn = buttons[next_index];
const block_type = target.dataset.block;
// make it red
document.body.classList.add( 'scrolling' );
smoothScroll( next_btn, { block: block_type })
.then( () => {
// remove the red
document.body.classList.remove( 'scrolling' );
} )
});
/*
*
* Promised based scrollIntoView( { behavior: 'smooth' } )
* #param { Element } elem
** ::An Element on which we'll call scrollIntoView
* #param { object } [options]
** ::An optional scrollIntoViewOptions dictionary
* #return { Promise } (void)
** ::Resolves when the scrolling ends
*
*/
function smoothScroll( elem, options ) {
return new Promise( (resolve) => {
if( !( elem instanceof Element ) ) {
throw new TypeError( 'Argument 1 must be an Element' );
}
let same = 0; // a counter
let lastPos = null; // last known Y position
// pass the user defined options along with our default
const scrollOptions = Object.assign( { behavior: 'smooth' }, options );
// let's begin
elem.scrollIntoView( scrollOptions );
requestAnimationFrame( check );
// this function will be called every painting frame
// for the duration of the smooth scroll operation
function check() {
// check our current position
const newPos = elem.getBoundingClientRect().top;
if( newPos === lastPos ) { // same as previous
if(same ++ > 2) { // if it's more than two frames
/* #todo: verify it succeeded
* if(isAtCorrectPosition(elem, options) {
* resolve();
* } else {
* reject();
* }
* return;
*/
return resolve(); // we've come to an halt
}
}
else {
same = 0; // reset our counter
lastPos = newPos; // remember our current position
}
// check again next painting frame
requestAnimationFrame(check);
}
});
}
p {
height: 400vh;
width: 5px;
background: repeat 0 0 / 5px 10px
linear-gradient(to bottom, black 50%, white 50%);
}
body.scrolling {
background: red;
}
<button data-block="center">scroll to next button <code>block:center</code></button>
<p></p>
<button data-block="start">scroll to next button <code>block:start</code></button>
<p></p>
<button data-block="nearest">scroll to next button <code>block:nearest</code></button>
<p></p>
<button>scroll to top</button>
You can use IntersectionObserver, check if element .isIntersecting at IntersectionObserver callback function
const element = document.getElementById("box");
const intersectionObserver = new IntersectionObserver((entries) => {
let [entry] = entries;
if (entry.isIntersecting) {
setTimeout(() => alert(`${entry.target.id} is visible`), 100)
}
});
// start observing
intersectionObserver.observe(element);
element.scrollIntoView({behavior: "smooth"});
body {
height: calc(100vh * 2);
}
#box {
position: relative;
top:500px;
}
<div id="box">
box
</div>
I stumbled across this question as I wanted to focus a particular input after the scrolling is done (so that I keep the smooth scrolling).
If you have the same usecase as me, you don't actually need to wait for the scroll to be finished to focus your input, you can simply disable the scrolling of focus.
Here is how it's done:
window.scrollTo({ top: 0, behavior: "smooth" });
myInput.focus({ preventScroll: true });
cf: https://github.com/w3c/csswg-drafts/issues/3744#issuecomment-685683932
Btw this particular issue (of waiting for scroll to finish before executing an action) is discussed in CSSWG GitHub here: https://github.com/w3c/csswg-drafts/issues/3744
Solution that work for me with rxjs
lang: Typescript
scrollToElementRef(
element: HTMLElement,
options?: ScrollIntoViewOptions,
emitFinish = false,
): void | Promise<boolean> {
element.scrollIntoView(options);
if (emitFinish) {
return fromEvent(window, 'scroll')
.pipe(debounceTime(100), first(), mapTo(true)).toPromise();
}
}
Usage:
const element = document.getElementById('ELEM_ID');
scrollToElementRef(elment, {behavior: 'smooth'}, true).then(() => {
// scroll finished do something
})
These answers above leave the event handler in place even after the scrolling is done (so that if the user scrolls, their method keeps getting called). They also don't notify you if there's no scrolling required. Here's a slightly better answer:
$("#mybtn").click(function() {
$('html, body').animate({
scrollTop: $("div").offset().top
}, 2000);
$("div").html("Scrolling...");
callWhenScrollCompleted(() => {
$("div").html("Scrolling is completed!");
});
});
// Wait for scrolling to stop.
function callWhenScrollCompleted(callback, checkTimeout = 200, parentElement = $(window)) {
const scrollTimeoutFunction = () => {
// Scrolling is complete
parentElement.off("scroll");
callback();
};
let scrollTimeout = setTimeout(scrollTimeoutFunction, checkTimeout);
parentElement.on("scroll", () => {
clearTimeout(scrollTimeout);
scrollTimeout = setTimeout(scrollTimeoutFunction, checkTimeout);
});
}
body { height: 2000px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="mybtn">Scroll to Text</button>
<br><br><br><br><br><br><br><br>
<div>example text</div>
i'm not an expert in javascript but i made this with jQuery. i hope it helps
$("#mybtn").click(function() {
$('html, body').animate({
scrollTop: $("div").offset().top
}, 2000);
});
$( window ).scroll(function() {
$("div").html("scrolling");
if($(window).scrollTop() == $("div").offset().top) {
$("div").html("Ended");
}
})
body { height: 2000px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="mybtn">Scroll to Text</button>
<br><br><br><br><br><br><br><br>
<div>example text</div>
I recently needed callback method of element.scrollIntoView(). So tried to use the Krzysztof Podlaski's answer.
But I could not use it as is. I modified a little.
import { fromEvent, lastValueFrom } from 'rxjs';
import { debounceTime, first, mapTo } from 'rxjs/operators';
/**
* This function allows to get a callback for the scrolling end
*/
const scrollToElementRef = (parentEle, childEle, options) => {
// If parentEle.scrollTop is 0, the parentEle element does not emit 'scroll' event. So below is needed.
if (parentEle.scrollTop === 0) return Promise.resolve(1);
childEle.scrollIntoView(options);
return lastValueFrom(
fromEvent(parentEle, 'scroll').pipe(
debounceTime(100),
first(),
mapTo(true)
)
);
};
How to use
scrollToElementRef(
scrollableContainerEle,
childrenEle,
{
behavior: 'smooth',
block: 'end',
inline: 'nearest',
}
).then(() => {
// Do whatever you want ;)
});
Is there anyway to call a method on vue after the viewer scrolled certain amount of page percentage?
For example, i would like to run a method to display an offer after the viewer has scrolled 80% of the page from top to bottom.
<script>
export default {
mounted() {
window.addEventListener("scroll", this.handleScroll);
},
destroyed() {
window.removeEventListener("scroll", this.handleScroll);
},
methods: {
handleScroll(event) {
// Any code to be executed when the window is scrolled
const offsetTop = window.scrollY || 0;
const percentage = (offsetTop * 100) / document.body.scrollHeight;
// Do something with the percentage
},
},
};
</script>
Note If you want to do something ( for example task() ) with a condition that the percentage is equal or greater than some value you must considering a data variable container that how many times that condition is true and do the operation just one time after that.
<script>
export default {
data() {
return {
reached: false, // checker container
};
},
methods: {
task() {
console.log("Triggered just one time >= 80");
},
handleScroll(event) {
// ... After calculating the percentage ...
if (percentage >= 80) {
if (!this.reached) {
this.task();
this.reached = true;
}
} else this.reached = false;
},
},
};
</script>
Live Demo
I have a react app, which renders the data on the screen. The URL is of the format <DOMAIN>/slug#entityId. Thus, after the view is loaded, I need to scroll to that specific #entityId provided as the id of the HTML element.
I am using React's componentDidUpdate() method to scroll to the ID after the render occurs.
componentDidUpdate () {
if(// data rendered into view) {
const id = this.entityId;
if (id) {
setTimeout(() => {
const element = document.getElementById(id);
if (element) {
element.scrollIntoView({
behavior: 'smooth'
});
}
}, 500);
}
}
}
Thus, the scroll to the ID happens before the images are loaded. This leads to the scroll not stopping at the expected place. The number of images is their resolution is variable.
Increasing the timeout to 1000ms does solve the issue. But is this an optimal solution?
with document ready
$(document).ready(function () {
if(// data rendered into view) {
const id = this.entityId;
if (id) {
setTimeout(() => {
const element = document.getElementById(id);
if (element) {
element.scrollIntoView({
behavior: 'smooth'
});
}
}, 500);
}
}
}
});
I have a website with different sections. I am using segment.io to track different actions on the page. How can I detect if a user has scrolled to the bottom of a div? I have tried the following but it seems to be triggered as soon as I scroll on the page and not when
I reached the bottom of the div.
componentDidMount() {
document.addEventListener('scroll', this.trackScrolling);
}
trackScrolling = () => {
const wrappedElement = document.getElementById('header');
if (wrappedElement.scrollHeight - wrappedElement.scrollTop === wrappedElement.clientHeight) {
console.log('header bottom reached');
document.removeEventListener('scroll', this.trackScrolling);
}
};
An even simpler way to do it is with scrollHeight, scrollTop, and clientHeight.
Subtract the scrolled height from the total scrollable height. If this is equal to the visible area, you've reached the bottom!
element.scrollHeight - element.scrollTop === element.clientHeight
In react, just add an onScroll listener to the scrollable element, and use event.target in the callback.
class Scrollable extends Component {
handleScroll = (e) => {
const bottom = e.target.scrollHeight - e.target.scrollTop === e.target.clientHeight;
if (bottom) { ... }
}
render() {
return (
<ScrollableElement onScroll={this.handleScroll}>
<OverflowingContent />
</ScrollableElement>
);
}
}
I found this to be more intuitive because it deals with the scrollable element itself, not the window, and it follows the normal React way of doing things (not using ids, ignoring DOM nodes).
You can also manipulate the equation to trigger higher up the page (lazy loading content/infinite scroll, for example).
you can use el.getBoundingClientRect().bottom to check if the bottom has been viewed
isBottom(el) {
return el.getBoundingClientRect().bottom <= window.innerHeight;
}
componentDidMount() {
document.addEventListener('scroll', this.trackScrolling);
}
componentWillUnmount() {
document.removeEventListener('scroll', this.trackScrolling);
}
trackScrolling = () => {
const wrappedElement = document.getElementById('header');
if (this.isBottom(wrappedElement)) {
console.log('header bottom reached');
document.removeEventListener('scroll', this.trackScrolling);
}
};
Here's a solution using React Hooks and ES6:
import React, { useRef, useEffect } from 'react';
const MyListComponent = () => {
const listInnerRef = useRef();
const onScroll = () => {
if (listInnerRef.current) {
const { scrollTop, scrollHeight, clientHeight } = listInnerRef.current;
if (scrollTop + clientHeight === scrollHeight) {
// TO SOMETHING HERE
console.log('Reached bottom')
}
}
};
return (
<div className="list">
<div className="list-inner" onScroll={() => onScroll()} ref={listInnerRef}>
{/* List items */}
</div>
</div>
);
};
export default List;
This answer belongs to Brendan, let's make it functional
export default () => {
const handleScroll = (e) => {
const bottom = e.target.scrollHeight - e.target.scrollTop === e.target.clientHeight;
if (bottom) {
console.log("bottom")
}
}
return (
<div onScroll={handleScroll} style={{overflowY: 'scroll', maxHeight: '400px'}} >
//overflowing elements here
</div>
)
}
If the first div is not scrollable it won't work and onScroll didn't work for me in a child element like div after the first div so onScroll should be at the first HTML tag that has an overflow
We can also detect div's scroll end by using ref.
import React, { Component } from 'react';
import {withRouter} from 'react-router-dom';
import styles from 'style.scss';
class Gallery extends Component{
paneDidMount = (node) => {
if(node) {
node.addEventListener("scroll", this.handleScroll.bind(this));
}
}
handleScroll = (event) => {
var node = event.target;
const bottom = node.scrollHeight - node.scrollTop === node.clientHeight;
if (bottom) {
console.log("BOTTOM REACHED:",bottom);
}
}
render() {
var that = this;
return(<div className={styles.gallery}>
<div ref={that.paneDidMount} className={styles.galleryContainer}>
...
</div>
</div>);
}
}
export default withRouter(Gallery);
Extending chandresh's answer to use react hooks and ref I would do it like this;
import React, {useState, useEffect} from 'react';
export default function Scrollable() {
const [referenceNode, setReferenceNode] = useState();
const [listItems] = useState(Array.from(Array(30).keys(), (n) => n + 1));
useEffect(() => {
return () => referenceNode.removeEventListener('scroll', handleScroll);
}, []);
function handleScroll(event) {
var node = event.target;
const bottom = node.scrollHeight - node.scrollTop === node.clientHeight;
if (bottom) {
console.log('BOTTOM REACHED:', bottom);
}
}
const paneDidMount = (node) => {
if (node) {
node.addEventListener('scroll', handleScroll);
setReferenceNode(node);
}
};
return (
<div
ref={paneDidMount}
style={{overflowY: 'scroll', maxHeight: '400px'}}
>
<ul>
{listItems.map((listItem) => <li>List Item {listItem}</li>)}
</ul>
</div>
);
}
Add following functions in your React.Component and you're done :]
componentDidMount() {
window.addEventListener("scroll", this.onScroll, false);
}
componentWillUnmount() {
window.removeEventListener("scroll", this.onScroll, false);
}
onScroll = () => {
if (this.hasReachedBottom()) {
this.props.onScrollToBottom();
}
};
hasReachedBottom() {
return (
document.body.offsetHeight + document.body.scrollTop ===
document.body.scrollHeight
);
}
I know this has already been answered but, I think another good solution is to use what's already available out in the open source community instead of DIY. React Waypoints is a library that exists to solve this very problem. (Though don't ask me why the this problem space of determining if a person scrolls past an HTML element is called "waypoints," haha)
I think it's very well designed with its props contract and definitely encourage you to check it out.
I used follow in my code
.modify-table-wrap {
padding-top: 50px;
height: 100%;
overflow-y: scroll;
}
And add code in target js
handleScroll = (event) => {
const { limit, offset } = this.state
const target = event.target
if (target.scrollHeight - target.scrollTop === target.clientHeight) {
this.setState({ offset: offset + limit }, this.fetchAPI)
}
}
return (
<div className="modify-table-wrap" onScroll={this.handleScroll}>
...
<div>
)
Put a div with 0 height after your scrolling div. then use this custom hooks to detect if this div is visible.
const bottomRef = useRef();
const reachedBottom = useCustomHooks(bottomRef);
return(
<div>
{search resault}
</div>
<div ref={bottomRef}/> )
reachedBottom will toggle to true if you reach bottom
To evaluate whether my browser has scrolled to the bottom of a div, I settled with this solution:
const el = document.querySelector('.your-element');
const atBottom = Math.ceil(el.scrollTop + el.offsetHeight) === el.scrollHeight;
The solution below works fine on most of browsers but has problem with some of them.
element.scrollHeight - element.scrollTop === element.clientHeight
The better and most accurate is to use the code below which works on all browsers.
Math.abs(e.target.scrollHeight - e.target.clientHeight - e.target.scrollTop) < 1
So the final code should be something like this
const App = () => {
const handleScroll = (e) => {
const bottom = Math.abs(e.target.scrollHeight - e.target.clientHeight - e.target.scrollTop) < 1;
if (bottom) { ... }
}
return(
<div onScroll={handleScroll}>
...
</div>
)
}
This answer belongs to Brendan, but I am able to use that code in this way.
window.addEventListener("scroll", (e) => {
const bottom =
e.target.scrollingElement.scrollHeight -
e.target.scrollingElement.scrollTop ===
e.target.scrollingElement.clientHeight;
console.log(e);
console.log(bottom);
if (bottom) {
console.log("Reached bottom");
}
});
While others are able to access directly inside target by
e.target.scrollHeight, I am able to achieve same by
e.target.scrollingElement.scrollHeight