How to scroll in jQuery with an animation? - javascript

I want to scroll my page 1750px from the top with an animation. I tried the following and it doesn't work.
$('#trailer').click(function() {
event.preventDefault();
//$(window).scrollTop(1750); // I want to animate this.
$(window).animate(
{top: 1750},
200);
return false;
});

You need to use scrollTop instead of top and you have to call animate on the body (or both html and body depending on the browser):
$('html, body').animate({
scrollTop: 1750
}, 200);
Fiddle

Related

Scroll to section in HTML/CSS

if I have the following JS code:
//Scroll Down button
$(window).scroll(function () {
if ($(this).scrollDown() > 100) {
$('.containerScroll').fadeIn('slow');
} else {
$('.containerScroll').fadeOut('slow');
}
});
$('.containerScroll').click(function () {
$('html, body').animate({
scrollTop: 0
}, 1500, 'easeInOutExpo');
return false;
});
This basically is for the Back-top-button animation where if the user clicks the button, then it brings the user back to the homepage with smooth scrolling. I would like the opposite. Is there a way to modify the above JS code so that when the user clicks the button, it brings the user to whichever page they desire? Right now, this scrolls all the way to the top and brings the user to only the homepage of the website, but how can I make it so it would bring the user to whichever page on the website?
This is what I have in HTML file:
<a href="#about" class="containerScroll">
<div class="first-scroll"></div>
<div class="second-scroll"></div>
</a>
Basically, I would like the user to go in the about section of the page instead of the homepage. Any suggestions on how to achieve this task?
You can set the scrollTop value to the offset of whatever element you want. For example:
$('html, body').scrollTop($('#about').offset().top);
will set scrollTop to the top of the element with id about by getting its offset.
Or you could use animate as you did in your example:
$('html, body').animate({
'scrollTop': $('#about').offset().top
}, 1500);
Fiddle
Fiddle smooth scroll
to top
window.scrollTo({
top: 0,
behavior: 'smooth'
});
to element
const element = getElementById("someElement");
//you can do it by jquery. no matter
element.scrollIntoView({behavior: "smooth", block: "end", inline: "nearest"});
MDM: scrolIntoView
MDM: scrollTo

Scroll Up/Down want to slide in parts not in once

I am using a slider on my web page for that i used jQuery Function
to scroll down
jQuery("#downClick").click(function() {
jQuery("html, body").animate({ scrollTop: jQuery(document).height() }, "slow");
});
to scroll up
jQuery("#upClick").click(function(){ //Click event to scroll to top ==>> Slider
jQuery('html, body').animate({scrollTop : 0},800);
return false;
});
My page is having too much data to display, so when a person clicks on this buttons either he navigates to bottom or top in once.
Does anybody can suggest me how can i change to something like if i want to scroll up it will scroll up with multiple steps not in once.
$('#upClick').on('click', function() {
var scrollIndex = $(window).scrollTop(); // current page position
$(window).scrollTop(y - 150); // scroll up 150px
}
refer this!

Animate Scroll Flex div to right from left

On click of a panel (say panel1) I am trying to animate scroll to the newly added panel (panel2) to left side of the screen.
I have tried
windows.location = '#p2' // panel2 id
but that doesn't animate and bluntly takes the focus to the new panel
Here is the JSFiddle .
Note: I am not sure jquery or CSS animations can be done here.
looking for CSS animations
You can do like this:
function addPanel(elemId) {
$('#'+elemId).css('display', 'flex');
$('html, body').animate({
scrollLeft: $('#'+elemId).offset().left
}, 1000, function() {
// Animation complete.
});
}
Working fiddle
You can use jQuery to animate your container so the new panel (panel2) is visible in the view port.
https://jsfiddle.net/wtfc8o2t/6/
function addPanel(elemId) {
document.getElementById(elemId).style.display = 'flex';
$( "#flex-container" ).animate({
left: "-=450"
}, 1000, function() {
// Animation complete.
});
}

Scroll to the top of the page after a sequence of divs

The code I have scrolls through a sequence of divs, each called .container. Each .container has a 100% height, so the user ends up quite far down the page as a result.
Now I am trying to scroll back to the top (using the same .container class) once the user reaches to the bottom of the page.
$('.down').click(function (e) {
var next_container = $(this)
.next(container);
$('html, body')
.animate({
scrollTop: next_container.offset().top
}, 'slow');
});
Is there way for the jQuery to detect that the user is at the bottom of the document, and as a result, scroll to the first .container (rather than the next)?
You can check that there is a next container found. If not, go to the first one:
$('.down').click(function (e) {
var next_container = $(this).next(container);
if (!next_container.length) {
next_container = $(container).first();
}
$('html, body').animate({
scrollTop: next_container.offset().top
}, 'slow');
});
This is assuming your container variable is a string with the selector of the element, ie. ".container"

Scroll to the top of the page using JavaScript?

How do I scroll to the top of the page using JavaScript? The scrollbar instantly jumping to the top of the page is desirable too as I'm not looking to achieve smooth scrolling.
If you don't need the change to animate then you don't need to use any special plugins - I'd just use the native JavaScript window.scrollTo() method -- passing in 0, 0 will scroll the page to the top left instantly.
window.scrollTo(xCoord, yCoord);
Parameters
xCoord is the pixel along the horizontal axis.
yCoord is the pixel along the vertical axis.
If you do want smooth scrolling, try something like this:
$("a[href='#top']").click(function() {
$("html, body").animate({ scrollTop: 0 }, "slow");
return false;
});
That will take any <a> tag whose href="#top" and make it smooth scroll to the top.
Better solution with smooth animation:
// this changes the scrolling behavior to "smooth"
window.scrollTo({ top: 0, behavior: 'smooth' });
Reference: https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollTo#Example
Try this to scroll on top
<script>
$(document).ready(function(){
$(window).scrollTop(0);
});
</script>
You don't need jQuery to do this. A standard HTML tag will suffice...
<div id="jump_to_me">
blah blah blah
</div>
<a target="#jump_to_me">Click Here To Destroy The World!</a>
All of these suggestions work great for various situations. For those who find this page through a search, one can also give this a try. JQuery, no plug-in, scroll to element.
$('html, body').animate({
scrollTop: $("#elementID").offset().top
}, 2000);
smooth scroll, pure javascript:
(function smoothscroll(){
var currentScroll = document.documentElement.scrollTop || document.body.scrollTop;
if (currentScroll > 0) {
window.requestAnimationFrame(smoothscroll);
window.scrollTo (0,currentScroll - (currentScroll/5));
}
})();
<script>
$(function(){
var scroll_pos=(0);
$('html, body').animate({scrollTop:(scroll_pos)}, '2000');
});
</script>
Edit:
$('html, body').animate({scrollTop:(scroll_pos)}, 2000);
Another way scroll with top and left margin:
window.scrollTo({ top: 100, left: 100, behavior: 'smooth' });
Really strange: This question is active for five years now and there is still no vanilla JavaScript answer to animate the scrolling… So here you go:
var scrollToTop = window.setInterval(function() {
var pos = window.pageYOffset;
if ( pos > 0 ) {
window.scrollTo( 0, pos - 20 ); // how far to scroll on each step
} else {
window.clearInterval( scrollToTop );
}
}, 16); // how fast to scroll (this equals roughly 60 fps)
If you like, you can wrap this in a function and call that via the onclick attribute. Check this jsfiddle
Note: This is a very basic solution and maybe not the most performant one. A very elaborated example can be found here: https://github.com/cferdinandi/smooth-scroll
<script>
$("a[href='#top']").click(function() {
$("html, body").animate({ scrollTop: 0 }, "slow");
return false;
});
</script>
in html
go top
With window.scrollTo(0, 0); is very fast
so i tried the Mark Ursino example, but in Chrome nothing happens
and i found this
$('.showPeriodMsgPopup').click(function(){
//window.scrollTo(0, 0);
$('html').animate({scrollTop:0}, 'slow');//IE, FF
$('body').animate({scrollTop:0}, 'slow');//chrome, don't know if Safari works
$('.popupPeriod').fadeIn(1000, function(){
setTimeout(function(){$('.popupPeriod').fadeOut(2000);}, 3000);
});
});
tested all 3 browsers and it works
i'm using blueprint css
this is when a client clicks "Book now" button and doesn't have the rental period selected, slowly moves to the top where the calendars are and opens a dialog div pointing to the 2 fields, after 3sec it fades
If you want to do smooth scrolling, please try this:
$("a").click(function() {
$("html, body").animate({ scrollTop: 0 }, "slow");
return false;
});
Another solution is JavaScript window.scrollTo method :
window.scrollTo(x-value, y-value);
Parameters :
x-value is the pixel along the horizontal axis.
y-value is the pixel along the vertical axis.
Scroll to top of page with animation:
window.scrollTo({ top: 0, behavior: 'smooth' });
A lot of users recommend selecting both the html and body tags for cross-browser compatibility, like so:
$('html, body').animate({ scrollTop: 0 }, callback);
This can trip you up though if you're counting on your callback running only once. It will in fact run twice because you've selected two elements.
If that is a problem for you, you can do something like this:
function scrollToTop(callback) {
if ($('html').scrollTop()) {
$('html').animate({ scrollTop: 0 }, callback);
return;
}
$('body').animate({ scrollTop: 0 }, callback);
}
The reason this works is in Chrome $('html').scrollTop() returns 0, but not in other browsers such as Firefox.
If you don't want to wait for the animation to complete in the case that the scrollbar is already at the top, try this:
function scrollToTop(callback) {
if ($('html').scrollTop()) {
$('html').animate({ scrollTop: 0 }, callback);
return;
}
if ($('body').scrollTop()) {
$('body').animate({ scrollTop: 0 }, callback);
return;
}
callback();
}
The old #top can do the trick
document.location.href = "#top";
Works fine in FF, IE and Chrome
Smooth scrolling & animation with vanilla Javascript, without jQuery
// Get the element
let topBtn = document.querySelector(".top-btn");
// On Click, Scroll to the page's top, replace 'smooth' with 'auto' if you don't want smooth scrolling
topBtn.onclick = () => window.scrollTo({ top: 0, behavior: "smooth" });
// On scroll, Show/Hide the btn with animation
window.onscroll = () => window.scrollY > 500 ? topBtn.style.opacity = 1 : topBtn.style.opacity = 0
body {
background-color: #111;
height: 5000px;
}
.top-btn {
all: unset;
position: fixed;
right: 20px;
bottom: 20px;
cursor: pointer;
transform:scale(1.8);
opacity: 0;
transition: .3s;
}
<button class="top-btn">🔝</button>
This will work:
window.scrollTo(0, 0);
$(".scrolltop").click(function() {
$("html, body").animate({ scrollTop: 0 }, "slow");
return false;
});
.section{
height:400px;
}
.section1{
background-color: #333;
}
.section2{
background-color: red;
}
.section3{
background-color: yellow;
}
.section4{
background-color: green;
}
.scrolltop{
position:fixed;
right:10px;
bottom:10px;
color:#fff;
}
<html>
<head>
<title>Scroll top demo</title>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<div class="content-wrapper">
<div class="section section1"></div>
<div class="section section2"></div>
<div class="section section3"></div>
<div class="section section4"></div>
<a class="scrolltop">Scroll top</a>
</div>
</body>
</html>
Non-jQuery solution / pure JavaScript:
document.body.scrollTop = document.documentElement.scrollTop = 0;
The equivalent solution in TypeScript may be as the following
window.scroll({
top: 0,
left: 0,
behavior: 'smooth'
});
$(document).scrollTop(0); also works.
Try this
<script>
$(window).scrollTop(100);
</script>
Pure JavaScript solution:
function scrollToTop() {
window.scrollTo({
top: 0,
behavior: 'smooth'
});
I write an animated solution on Codepen
Also, you can try another solution with CSS scroll-behavior: smooth property.
html {
scroll-behavior: smooth;
}
#media (prefers-reduced-motion: reduce) {
html {
scroll-behavior: auto;
}
}
Try this code:
$('html, body').animate({
scrollTop: $("div").offset().top
}, time);
div => Dom Element where you want to move scroll.
time => milliseconds, define the speed of the scroll.
Why don't you use JQuery inbuilt function scrollTop :
$('html, body').scrollTop(0);//For scrolling to top
$("body").scrollTop($("body")[0].scrollHeight);//For scrolling to bottom
Short and simple!
You dont need JQuery. Simply you can call the script
window.location = '#'
on click of the "Go to top" button
Sample demo:
output.jsbin.com/fakumo#
PS: Don't use this approach, when you are using modern libraries like angularjs. That might broke the URL hashbang.
Motivation
This simple solution works natively and implements a smooth scroll to any position.
It avoids using anchor links (those with #) that, in my opinion, are useful if you want to link to a section, but are not so comfortable in some situations, specially when pointing to top which could lead to two different URLs pointing to the same location (http://www.example.org and http://www.example.org/#).
Solution
Put an id to the tag you want to scroll to, for example your first section, which answers this question, but the id could be placed everywhere in the page.
<body>
<section id="top">
<!-- your content -->
</section>
<div id="another"><!-- more content --></div>
Then as a button you can use a link, just edit the onclick attribute with a code like this.
<a onclick="document.getElementById('top').scrollIntoView({ behavior: 'smooth', block: 'start', inline: 'nearest' })">Click me</a>
Where the argument of document.getElementById is the id of the tag you want to scroll to after click.
If you don't want smooth scrolling, you can cheat and stop the smooth scrolling animation pretty much as soon as you start it... like so:
$(document).ready(function() {
$("a[href='#top']").click(function() {
$("html, body").animate({ scrollTop: 0 }, "1");
$('html, body').stop(true, true);
//Anything else you want to do in the same action goes here
return false;
});
});
I've no idea whether it's recommended/allowed, but it works :)
When would you use this? I'm not sure, but perhaps when you want to use one click to animate one thing with Jquery, but do another without animation? ie open a slide-in admin login panel at the top of the page, and instantly jump to the top to see it.
Simply use this script for scroll to top direct.
<script>
$(document).ready(function(){
$("button").click(function(){
($('body').scrollTop(0));
});
});
</script>
You can use javascript's built in function scrollTo:
function scroll() {
window.scrollTo({
top: 0,
behavior: 'smooth'
});
}
<button onclick="scroll">Scroll</button>

Categories

Resources