Check if user scrolled beyond certain amount - javascript

I need show button backtotop only if user has scrolled beyond > 250. How I can do it?
My code:
<template>
<div>
<button v-if="checkScroll" class="goTop" #click="backToTop">
<i class="fa fa-angle-up" aria-hidden="true"></i>
</button>
</div>
</template>
<script>
export default {
methods: {
computed: {
checkScroll() {
if ($(document).scrollTop() > 250) {
return true;
} else {
return false;
}
}
},
backToTop() {
this.$scrollTo('html');
},
}
}
</script>
My code is not working. Errors I do not get. Button is hidden.

Also don't forget to destroy the event:
new Vue({
el: "#app",
data() {
return {
scroll: null
}
},
methods: {
handleScroll(e) {
this.scroll = window.scrollY || window.scrollTop
}
},
created() {
window.addEventListener('scroll', this.handleScroll);
},
destroyed() {
window.removeEventListener('scroll', this.handleScroll);
}
})
html {
height: 3000px; /* some random height for demonstration purpose */
}
button {
position: fixed;
}
<script src="https://cdn.jsdelivr.net/npm/vue#2.6.2/dist/vue.js"></script>
<!-- scroll to see the button -->
<div id="app">
<button v-show="scroll > 250">foobar</button>
</div>

Use the onScroll event in Javascript to detect when the user scrolls down/up and use scrollTop() to automatically move to the top of the page when the button is clicked.
Make sure it is position:fixed;.
For more info, check out these:
onScroll
scrollTop()
To show/hide the button just change it's size using HTML DOM methods. For example:
document.getElementsByClassName("goTop")[0].width = 30;

codepen.io has great sketches for in demand features like this all for free. here is a scroll to top functionality page you can tweak to fit your needs hopefully https://codepen.io/rolandtoth/pen/eMamVK
.scrolltop-wrap {
$size: 3rem;
$offsetBottom: 2rem;
$offsetHorizontal: 2rem;
$scrollToRevealDistance: 12rem; // scroll offset to reveal scroll-to-top link
It's all scss instead of javascript. Here is a scss to css generator you can use, https://www.cssportal.com/scss-to-css/

Related

How to use IntersectionObserver API to make navBar sticky

I am making the clone of a webpage which is made in JS but I am developing it by HTML, CSS, JS. Its navBar looks like this . Here is the link if you want to experience yourself link.
So, I have tried to implement this using IntersectionObserver API as well as by using window.addEventListener(). I don't want to implement this by using scroll event Listener because it is too heavy for end user.
const intersectionCB = ([entry]) => {
const elem = entry.target;
if (!entry.isIntersecting) {
elem.classList.add('nav__2-sticky');
// observer.unobserve(navBar);
} else {
elem.classList.remove('nav__2-sticky');
}
};
const observer = new IntersectionObserver(intersectionCB, {
root: null,
threshold: 0
});
observer.observe(navBar);
In HTML file
<div class="nav__2">
<div class="row nav__2--content">
<div class="logo-container">
<img src="img/logo-black.png" alt="" class="logo" />
</div>
........
In SCSS file
.nav {
&__2 {
top: 8rem;
position: absolute;
left: 0;
width: 100%;
&-sticky {
position: fixed;
top: 0;
}
}
}
You might understand what is happening. When navBar gets out of the view, (navBar is positioned at 8rem from top!). I append nav__2-sticky class (which is positioned fixed at 0 from top) to appear on the screen. Due to which entry.isIntersecting becomes true and elem.classList.remove('nav__2-sticky'); is executed. As a result navBar again gets out of the view and again elem.classList.add('nav__2-sticky') is executed. This cycle of adding and removing classes due to entry.isIntersecting becoming True and False is creating a problem for me. This happens in such speed that it shows abnormal behaviour.
So, is there any proper solution for this? I would also like to hear other solutions that might work.
I used scroll event after all. Here is the code, I think I don't need to explain. You will get more detailed explanation here link
const initialCords = navBar.getBoundingClientRect();
document.addEventListener('scroll', () => {
if (window.scrollY > initialCords.top) {
navBar.classList.add('nav__2-sticky');
} else {
navBar.classList.remove('nav__2-sticky');
}
});
Another angle could be to run the intersection observer on an element that is out of view (below the bottom of the screen) and not only the navbar itself

Vue 3 - Always scroll to specific position on page when component appears

I have a basic form component and that shows up once I click a button (router is not used). I want the scroll position of the form to scroll down a bit (ex. y-axis of 40) once the form shows up, but I'm not entirely sure how to achieve this. There are various examples about this, but I couldn't get any of them to work. Can someone kindly advice a solution for this, please? I also started using vue 3.
<template>
<div class="appointment-wrapper" :class="[showForm ? 'appointment' : 'appointment-success']">
// Scroll down to a certain point
// ....
<form #submit.prevent="validateForm" novalidate>
// ....
</form>
</div>
</div>
</template>
If you need to scroll to an element position
document.getElementById(el).scrollIntoView();
Or if you need to scroll by the axis
window.scrollTo(0, 1000)
you can use window.scrollTo(0, 40) if the condition is true after you clicked the button.
Vue.createApp({
data() {
return {
showForm: true
}
},
mounted() {
if (this.showForm) window.scrollTo(0, 400) // only demo value - use 40
}
}).mount('#options-api')
#options-api {
height: 1000px;
}
<script src="https://unpkg.com/vue#next"></script>
<div id="options-api">
<h1>hidden title</h1>
</div>

I am currently removing jquery from my code and I am not able to convert this Jquery to Javascript

I am currently removing the Jquery from my website but i am not able to successfully convert it to JavaScript. I know its probably very stupid but i am still a beginner. Could anyone help?
$(document).scroll(function(){
$('.navbar').toggleClass('scrolled', $(this).
scrollTop() > $('.navbar').height());
});
You can try something like this:
window.onscroll = function() {
var nav = document.querySelector('.navbar');
var isScrolled = document.body.scrollTop > nav.offsetHeight || document.documentElement.scrollTop > nav.offsetHeight;
nav.classList.toggle("scrolled", isScrolled);
};
.container {
height: 2000px;
}
.nav-link {
display: block;
color: red;
}
.scrolled .nav-link {
color: blue;
}
<div class="container">
<div class="navbar">
Navbar
<a class="nav-link">aaa</a>
<a class="nav-link">bbb</a>
<a class="nav-link">ccc</a>
</div>
</div>
We're subscribing to the window's onscroll event. We grab a reference to your navbar element using document.querySelector(). Then we use that elements height (offsetHeight) to determine if it should have the .scrolled class. Finally, we use the toggle() method on the navbar element's classList property.
UPDATE based on comments:
If you must have many separate functions to handle the same event, you're better off using the window.addEventListener() syntax.
window.addEventListener('scroll', function() {
var nav = document.querySelector('.navbar');
var isScrolled = document.body.scrollTop > nav.offsetHeight || document.documentElement.scrollTop > nav.offsetHeight;
nav.classList.toggle("scrolled", isScrolled);
});
window.addEventListener('scroll', function() {
// ...
console.log('scroll b');
});
window.addEventListener('scroll', function() {
// ...
console.log('scroll c');
});
.container {
height: 2000px;
}
<div class="container">
<div class="navbar">Navbar</div>
</div>
The first line can be replaced it with an "addEventListener" like this
window.addEventListener('scroll', function (e) {
});
to replace the toggle function you can use the "classList" property. Save the element in a new variable and then "element.classList.remove('class')" or "element.classList.add('class')
var navbar = document.getElementById("navbar");
navbar.classList.remove("scrolled");
navbar.classList.add("scrolled");
Use this.scrollY to get the window ScrollY position, and element.clientHeight to get the height of the element including paddings (there are others methods to get the height that can fit more to your needs)
if (this.scrollY > navbar.clientHeight) {}
The end result will be something like this
window.addEventListener('scroll', function (e) {
var navbar = document.getElementById("navbar");
navbar.classList.remove("scrolled");
if (this.scrollY > navbar.clientHeight) {
navbar.classList.add("scrolled");
}
});

React.js keep scroll at bottom

I have a div that grows in height as an animation. Instead of growing outside of the viewable area (and user having to scroll down), I'd like the window to automatically scroll with the div height. Locking the scroll position at the bottom of the page would work.
!!This is in React!!
I've tried millions of google/SO answers, none work/ arent specific enough.
code https://github.com/coryb08/corydbaker npm install && npm start
You provided very little information, but since we know it's in React, you could use JavaScript to make sure your div is scrolled all the way to the bottom at all all times.
class FullMenu extends Component {
constructor() {
super()
this.state = {
class: "",
div: ""
}
this.scrollToBottom = this.scrollToBottom.bind(this);
}
componentDidMount() {
setInterval(this.scrollToBottom, 20);
}
scrollToBottom() {
var scrollingElement = (document.scrollingElement || document.body); /* you could provide your scrolling element with react ref */
scrollingElement.scrollTop = scrollingElement.scrollHeight;
}
render() {
return (
<div id="FullMenu">
{this.state.div}
<div id="triangleDiv">
<img
className={this.state.class}
onClick={() => {
this.setState({ class: "bounce" })
let that = this
setTimeout(function() {
that.setState({
class: "",
div: <div className="menuDiv" />
})
}, 1000)
}}
src={triangle}
id="triangle"
/>
</div>
</div>
)
}
}
Note that above solution keeps the window scrolled at all times. If you wanted to scroll it only during animation, then you should use react's CSSTransitionGroup and use clearInterval to stop this behavior in transitionEnd lifecycle hook.
You can use CSS alone
all you have to do is set the div styling
display: flex;
flex-direction: column-reverse
this should flip the div scroll and position it at the bottom

How to detect if the user has scroll 100px from current position

I have a one-page website where I am adding a class while the user clicks on nav. However, if the user has scroll 100px from the current location the class need to remove.
DEMO gh pages link
//working fine
var scrollvalue = 0;
$('a.js-scroll-trigger[href*="#"]:not([href="#"])').click(function() {
scrollvalue = $(window).scrollTop();
$(".copyright").addClass("activecopy");
});
//not working fine
$(window).scroll(function() {
if($(window).scrollTop() > 100) {
$('.copyright').removeClass('activecopy');
}
});
Note: I have already read stackoverflow post such as post1 and post2
It's a little hard to figure out what exactly the problem is as you have no shared the corresponding HTML markup. Try the following and let me know if it helps.
var scrollvalue = 0;
$('a.js-scroll-trigger[href*="#"]:not([href="#"])').click(function () {
scrollvalue = $(window).scrollTop();
$(".copyright").addClass("activecopy");
});
$(window).scroll(function () {
if (($(window).scrollTop() - scrollvalue) > 100) {
$('.copyright').removeClass('activecopy');
}
});
EDIT:
As I said, it's hard to see what's happening because you haven't shared markup. Here is a sample. Hope it helps.
EDIT 2:
To make this generic, you can wrap your code which registers for click listeners and scroll listeners in a function which accepts which elements to operate on as arguments. Sample Below.
function registerScrollTrigger(anchor, target) {
var $a = $(anchor);
var $t = $(target);
$a.click(function() {
//Get scroll position at the time of the click
var currentScroll = $(window).scrollTop();
function handleScroll() {
// Demo code to show current scroll on the screen
$t.html('Current Scroll: ' + ($(window).scrollTop() - currentScroll));
// Check if the user has scrolled 100px since clicking the tag
if (($(window).scrollTop() - currentScroll) > 100) {
// Remove active class from element
$t.removeClass('active');
// Demo code ti indicate that the scroll to 100px is complete
$t.html('Complete');
// Stop listening for scroll events [Optional but recommmended]
$(window).off('scroll', handleScroll);
}
}
// Add active class to element [Make it blue]
$t.addClass('active');
// Listen for scroll event and check if 100px has passed
$(window).scroll(handleScroll);
});
}
registerScrollTrigger('#a1', '#scroll1');
registerScrollTrigger('#a2', '#scroll2');
div.scroll {
margin-top: 50px;
}
div.scroll.active {
background: blue;
color: white;
}
div#pad {
height: 1000px;
}
h4 {
margin-bottom: 500px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<h4>Scroll Down For the Button</h4>
<a id="a1" class="js-scroll">Click Me </a>
<div id="scroll1" class="scroll">
Start scrolling after clicking the above button
</div>
<h4>Scroll Down For Another Button</h4>
<a id="a2" class="js-scroll">Click Me Too</a>
<div id="scroll2" class="scroll">
Start scrolling after clicking the above button
</div>
<div id="pad"></div>
Note:
You can also do something similar by setting a data-target attribute on the anchor which can be used to determine which item to add the class to and remove the class from instead of passing both items as a parameter
$(window).scroll(function() {
var height = $(window).scrollTop();
if (height > 100) {
$(".copyright").addClass("activecopy");
} else {
$('.copyright').removeClass('activecopy');
}
});
I am using this for showing my gototop button in bottom. Hope this will works for you.....

Categories

Resources