How scroll end page with vue js - javascript

How do I scroll to the bottom of the page?
scroll(){
let container = this.$el.querySelector('#scrollingChat')
container.scrollTop = container.scrollHeight
}
I'm doing this, and always calling my api answers, but it does not go to the bottom of the page

window.scrollTo(0, document.body.scrollHeight || document.documentElement.scrollHeight);
This is will instantly scroll to the bottom of any page.

If you create an anchor in your page like so:
<div id="top"></div>
you can use:
let elmnt = document.getElementById('top');
elmnt.scrollIntoView(false);
This page explains what the different alignment parameters do for scrollIntoView:
true - scrolls to top of element
false - scrolls to bottom of element
default it true
https://www.w3schools.com/jsref/met_element_scrollintoview.asp

window.scrollTo(0,document.body.scrollHeight);
or you can use smooth scroll: https://github.com/alamcordeiro/vue-smooth-scroll

You may take a look at Mozilla Docs as reference.
Code wise safest use with VueJS is, using nextTick() and ref attribution, especially if execution is triggered following an event (Example: Button Click). + works best if you use some VueJS framework.
Scroll can be applied with smooth behavior for a nicer UX.
Example for specific div
<template><div ref="myScrollTarget">...</div></template>
<script>
...
methods: {
scrollToBottom() {
const targetRef = this.$refs.myScrollTarget;
this.$nextTick(() => {
targetRef.scrollTo(
{
top: targetRef.scrollHeight,
left: 0,
behavior: "smooth"
}
);
});
}
}
...
</script>
Example for full page (window)
<template><div>...</div></template>
<script>
...
methods: {
scrollToBottom() {
this.$nextTick(() => {
window.scrollTo(
{
top: document.body.scrollHeight,
left: 0,
behavior: "smooth"
}
);
});
}
}
...
</script>

Related

How i make my button "go to top" work, he dosn't work

I write the code but when i click on the button he don't go up to the header as he have to do
(function() {
'use-strict'
function checkScroll() {
let scrolled = window.pageYOffset;
let coords = document.documentElement.clientHeight;
if (scrolled > coords) {
goTopBtn.classList.add('up_show');
}
if (scrolled < coords) {
goTopBtn.classList.remove('up_show');
}
}
function downToUp() {
if (window.pageXOffset > 0) {
window.scrollBy(0, -80);
setTimeout(downToUp, 0);
}
}
let goTopBtn = document.querySelector(".down_to_up");
window.addEventListener('scroll', checkScroll);
goTopBtn.addEventListener('click', downToUp);
})();
idk what i have to do
I wrote you a short summary of how I program To-Top buttons most of the time. I didn't quite understand the CheckScroll function. Should the to top button only be shown when the user has scrolled down a specific amount of pixels?
If yes I can add to my answer.
HTML-Code:
<button id="scroll-to-top-button">
Scroll to top
</button>
Variant 1 - scroll to top of page:
// select the button
const scrollToTopButton = document.getElementById('scroll-to-top-button');
// listen for clicks on the button
scrollToTopButton.addEventListener('click', () => {
window.scrollTo({
top: 0, // specifies Y position
behavior: 'smooth', // creates a smooth scroll effect
});
});
Variant 2 - scroll to specific element:
// listen for clicks on the button
const scrollToTopButton = document.getElementById('scroll-to-top-button');
// listen for the click event
scrollToTopButton.addEventListener('click', () => {
// select header element
const header = document.querySelector('header');
// scroll to the header element
header.scrollIntoView({
behavior: 'smooth', // creates a smooth scroll effect
});
});
So, the use strict, it is written with a space, not a hyphen!
You need to refer to the comment:
isn't it pageYOffset?
Blessings

Jump to right side of html page

I have an HTML page with a big table and many columns, I need to scroll right of page automatically on page load.
I've tried this code but it doesn't work for me :
</script><script type="text/javascript">
var myDiv = document.getElementById('containerDiv');
myDiv.innerHTML = variableLongText;
myDiv.scrollRight = 0;
</script>
Is it a correct approch to auto scroll the page?
You can try this code.
<script type="text/javascript">
var myDiv = document.getElementById('containerDiv');
myDiv.scrollTo(0, myDiv.scrollRight)
</script>
Try like this:
// Getting div from DOM
const myDiv = document.getElementById('containerDiv');
// Getting div's position
divRect = myDiv.getBoundingClientRect();
// Scrolling to div's position
window.scrollTo({
top: divRect.top,
left: divRect.left,
// behavior: 'smooth'
});
/*
behavior: 'smooth' will give a smooth sensation with a slow transition on scroll.
I would personally recommend using it (mainly if this is not intended to run on load).
*/
Better & without comments:
const divRect = document.getElementById('containerDiv').getBoundingClientRect();
window.scrollTo({ top: divRect.top, left: divRect.left });
For information about getBoundingClientRect(), check this article https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect
if you want to scroll window then use
window.scrollTo(x-axis,y-axis);
or for specific div use
document.getElementById('container').scrollLeft += 10000;
so full program be like
window.onload = function() {
// for specific div
document.getElementById('nan').scrollLeft += 100000;
//for window
/* window.scrollTo(10000, 0) */;
};
you can also see example
https://jsfiddle.net/zcmhp2de/38/

How can I make a button that scrolls back to the top of the page when you click on it

but when your fully at the top it disappears and when you scroll down a but it stays there.
Here is the Javascript for it
btnScrollToTop.addEventListener("click", function() {
window.scrollTo({
top: 0,
left: 0,
behavior: "smooth"
});
});
The arrow button scrolls to the top of the page when you press on it.
Here is the top of the page
What I want to do is so when your at the top of the page the button disappears but when you scroll a little it comes back so you can press it. Is there any simple way to do that?
First, add an event listener on the page scroll. In the event handler, change the button display accordingly to scroll position.
Then, set your button display to none by default.
Beware: if the user comes back on the page, without scrolling, the button won't be shown even if the page is scrolled. To prevent this, call the event handler on page load.
const scrollHandler = () => {
const scrollPosition = window.scrollY
if ( scrollPosition > 0) {
btnScrollTop.style.display = 'block'
} else {
btnScrollTop.style.display = 'none'
}
}
document.addEventListener('scroll', scrollHandler)
window.onload = scrollHandler
Using the Intersection observer would probably be the right approach.
Code Description: What the code below is doing here is - changing the CSS display property of the element with ID buttonID to none when the element with ID topSectionID is 100% visible on the screen.
const topSection = document.getElementById("topSectionID");
let options = {
root: null,
rootMargin: "0px",
threshold: 1.0,
};
let callback = (entries, observer) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
document.getElementById("buttonID").style.display = 'none'
} else {
document.getElementById("buttonID").style.display = 'block';
}
});
};
let observer = new IntersectionObserver(callback, options);
observer.observe(topSection);
Here threshold: 1.0 means - execute the intersection observer when 100% of the topSectionID is visible

How to trigger event in JS when reaching the bottom of the page in cases where there's no scroll

I have an event listener for scrolling to the bottom of the page that works fine:
document.addEventListener('scroll', () => {
if (window.innerHeight + window.pageYOffset >= document.body.offsetHeight) {
console.log("bottom reached");
}
});
BUT my issue is that if the page loads and the document is shorter than the window, this won't trigger because there's no scroll event. The document fits in the window, in other words, so no need to scroll to the bottom.
I still want to trigger something in this case, though. How do I do that?
I thought about just having a conditional statement within a DOMContentLoaded event listener that checks if the window is bigger than the document, i.e.
if (window.innerHeight + window.pageYOffset >= document.body.offsetHeight) {
console.log("window size exceeds page size");
}
While this works, it gives me a "forced reflow" performance violation warning in the console, basically saying this is taking too long.
Any advice on how to handle this?
Your solution is the simplest and if you do not have any other problems with it rather than the warning in the console, it might be the best.
Another way would be to use the Intersection Observer API, which is executed on load.
Here is a simple example:
<head>
<style>
.container {
width: 100%;
height: 80%;
background-color: whitesmoke;
}
</style>
</head>
<body>
<div class="container"></div>
<script>
const container = document.querySelector('.container')
const observer = new IntersectionObserver(callback, {
root: null, // intersect with viewport
rootMargin: '0px', // no margin when computing intersections
threshold: 1.0, // execute callback when every pixel is visible
})
function callback(entries) {
for (const entry of entries) {
if (entry.isIntersecting) {
console.log("i am also fired on load")
}
}
}
observer.observe(container)
</script>
</body>
You could also observe your footer or some element at the bottom of the page. Using Intersection Observer you do not even have to use the scroll event listener.

Javascript - Efficiency for scroll event, run code only once

These if statements are always making me dizzy. If have a page with a header, and a hidden header above that in the markup.
<div id="headerfloat" style="display:none;">
<p>Floated header</p>
</div>
<div id="header">
<p>Header</p>
</div>
The idea is that whenever the page is scrolled down more than 225px, the #headerfloat should appear, and dissapear when topScroll is less than 225px. And I managed to get this working with javascript and jQuery, but when I test it on iPhone, it's very sluggish. And I'm pretty sure it's because the code is run at each scroll event. And even if #headerfloat is visible, the code still executes. Even though it doesn't have to at that point.
So, I need to make sure the code only run once, when it's needed. My first thought was to add and remove classes like .open and .closed to #headerfloat. And run if statements on those during the scroll event. But is that the most efficient way of doing it?
My so far, ugly snippet:
jQuery(window).scroll(function () {
var headerfloat = $("#header_float");
var top = jQuery(window).scrollTop();
if (top > 225) // height of float header
{
if (!$(headerfloat).hasClass("closed")) {
$(headerfloat).addClass("boxshadow", "", 100, "easeInOutQuad").slideDown().addClass("open").removeClass("closed");
}
} else {
$(headerfloat).removeClass("boxshadow", "", 100, "easeInOutQuad").removeClass("closed").slideUp();
}
});
Edit: So after laconbass's awesome response, this is the code I ended up with:
var mainHeader = $('#header')
, top_limit = mainHeader.outerHeight()
, $window = $(window)
;
var header_float = $('#header_float')
bindEvent();
function bindEvent() {
$window.scroll( scrollEvent );
}
function scrollEvent() {
var top = $window.scrollTop();
// avoid any logic if nothing must be done
if ( top < top_limit && !header_float.is(':visible')
|| top > top_limit && header_float.is(':visible')
) return;
// unbind the scroll event to avoid its execution
// until slide animation is complete
$window.unbind( 'scroll' );
// show/hide the header
if ( top > top_limit ) {
header_float.slideDown( 400, bindEvent );
} else {
header_float.slideUp( 400, bindEvent );
}
};
The snippet you started from seems a bit ugly.
I've made one on jsfiddle for your pleasure and reference
I've assumed the following:
you want a fixed positioned header when the page scrolls down (aka fixed header).
fixed headed is a clone of the page main header, with the class fixed.
fixed header is shown when the page scrolls down more than the header height.
fixed header is hidden when the page scrolls up enough to show the main page header.
Performance tips:
cache the jQuery objects to avoid making a new query each time the event handler is executed.
unbind the event handler before the show/hide animations, rebind it after.
on the event handler, return as soon as posible to avoid unnecesary logic. Remember while JavaScript is executed the browser render process is blocked.
var mainHeader = $('header')
, header = mainHeader.clone().addClass('fixed').appendTo('body')
, top_limit = header.outerHeight()
;
bindEvents();
function bindEvents() {
$(window).scroll( scrollEvent );
}
function scrollEvent() {
var top = $(window).scrollTop();
// avoid any logic if nothing must be done
if ( top < top_limit && !header.is(':visible')
|| top > top_limit && header.is(':visible')
) return;
// unbind the scroll event to avoid its execution
// until slide animation is complete
$(window).unbind( 'scroll' );
// show/hide the header
if ( top > top_limit ) {
header.slideDown( 400, bindEvents );
} else {
header.slideUp( 400, bindEvents );
}
};
<header>
<h1>Awesome header</h1>
</header>
<div>
<!-- the page content -->
</div>
/* the real code needed */
header.fixed {
display: none;
position: fixed;
top: 0;
}
two way:
1,on scroll,and if you have done your want, remove the scroll event.
2,var a variable,default is false, on scroll, if the variable is false,to do you want,and set the variable to true; if the variable is true already, do nothing(or others you want)

Categories

Resources