I am using the following javascript code to scroll my div into view when a user click on a div.
<script>
function showDiv2() {
document.getElementById('about').style.display = "none";
document.getElementById('terms').style.display = "none";
document.getElementById('breaker').style.display = "block";
document.getElementById('contact_us').style.display = "block";
document.getElementById( 'contact_us' ).scrollIntoView('slow');
}
</script>
this code works and scrolls the div into view, but there is no effect, instead of the page scrolling smoothly down to my div it sort of just jumps to the div. Is there a way I can make this smoothly and slowly scroll down to my div? Thanks
According to Element.scrollIntoView() documentation try this:
element.scrollIntoView({block: "end", behavior: "smooth"});
but you must remember that this is an experimental feature and works good only in Firefox
For a more comprehensive list of methods for smooth scrolling, see my answer here.
To scroll to a certain position in an exact amount of time, window.requestAnimationFrame can be put to use, calculating the appropriate current position each time. To scroll to an element, just set the y-position to element.offsetTop.
/*
#param pos: the y-position to scroll to (in pixels)
#param time: the exact amount of time the scrolling will take (in milliseconds)
*/
function scrollToSmoothly(pos, time) {
var currentPos = window.pageYOffset;
var start = null;
if(time == null) time = 500;
pos = +pos, time = +time;
window.requestAnimationFrame(function step(currentTime) {
start = !start ? currentTime : start;
var progress = currentTime - start;
if (currentPos < pos) {
window.scrollTo(0, ((pos - currentPos) * progress / time) + currentPos);
} else {
window.scrollTo(0, currentPos - ((currentPos - pos) * progress / time));
}
if (progress < time) {
window.requestAnimationFrame(step);
} else {
window.scrollTo(0, pos);
}
});
}
Demo:
function scrollToSmoothly(pos, time) {
var currentPos = window.pageYOffset;
var start = null;
if(time == null) time = 500;
pos = +pos, time = +time;
window.requestAnimationFrame(function step(currentTime) {
start = !start ? currentTime : start;
var progress = currentTime - start;
if (currentPos < pos) {
window.scrollTo(0, ((pos - currentPos) * progress / time) + currentPos);
} else {
window.scrollTo(0, currentPos - ((currentPos - pos) * progress / time));
}
if (progress < time) {
window.requestAnimationFrame(step);
} else {
window.scrollTo(0, pos);
}
});
}
document.getElementById("toElement").addEventListener("click", function(e){
scrollToSmoothly(document.querySelector('div').offsetTop, 500 /* milliseconds */);
});
document.getElementById("backToTop").addEventListener("click", function(e){
scrollToSmoothly(0, 500);
});
<button id="toElement">Scroll To Element</button>
<div style="margin: 1000px 0px; text-align: center;">Div element
<button id="backToTop">Scroll back to top</button>
</div>
The SmoothScroll.js library can also be used, which supports scrolling to an element on the page in addition to more complex features such as smooth scrolling both vertically and horizontally, scrolling inside other container elements, different easing behaviors, scrolling relatively from the current position, and more.
document.getElementById("toElement").addEventListener("click", function(e){
smoothScroll({toElement: document.querySelector('div'), duration: 500});
});
document.getElementById("backToTop").addEventListener("click", function(e){
smoothScroll({yPos: 'start', duration: 500});
});
<script src="https://cdn.jsdelivr.net/gh/LieutenantPeacock/SmoothScroll#1.2.0/src/smoothscroll.min.js" integrity="sha384-UdJHYJK9eDBy7vML0TvJGlCpvrJhCuOPGTc7tHbA+jHEgCgjWpPbmMvmd/2bzdXU" crossorigin="anonymous"></script>
<button id="toElement">Scroll To Element</button>
<div style="margin: 1000px 0px; text-align: center;">Div element
<button id="backToTop">Scroll back to top</button>
</div>
Related
I have a page "link.html" which has an anchor pointing to index.html page <a href = "index.html?#myInnerLink"
I want smoothscroll to the div on another page(index.html) which has an Id of "myInnerLink" in jquery .. it is working fine but the problem is that it is scrolling from bottom to top instead of top to bottom to that particular div
"myInnerLink" div is internal in "myDiv" div... Thanks
link.html
<a id="mylink" href="index.html?#myInnerLink">Go To MY InnerLink</a>
index.html
<div id="myDiv" class="mydiv">
SomeText here...
<div id="myInnerLink">
ScrollTo This Div...
</div>
</div>
jquery
$(document).ready(function() {
if (window.location.hash) {
var hash = window.location.hash;
$('#myDiv').animate({
scrollTop : $(hash).offset().top
}, 500);
};
});
I'm currently using this script below, which is modified and originally came from https://jsfiddle.net/s61x7c4e/
function doScrolling(element, duration) {
let bodyRect = document.body.getBoundingClientRect(),
elementRect = element.getBoundingClientRect(),
offset = ((elementRect.top - bodyRect.top) - 40);
let startingY = window.pageYOffset,
elementY = offset,
targetY,
diff,
easeInOutCubic,
start;
duration = duration || 500;
// if element is close to page's bottom then window will scroll only to some position above the element...
targetY = document.body.scrollHeight - elementY < window.innerHeight ? document.body.scrollHeight - window.innerHeight : elementY;
diff = targetY - startingY;
easeInOutCubic = function (t) {
return t < .5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1
};
if (!diff) return;
// bootstrap our animation,
// it will get called right before next frame shall be rendered...
window.requestAnimationFrame(function step(timestamp) {
if (!start) start = timestamp;
let time = timestamp - start, // elapsed milliseconds since start of scrolling...
percent = Math.min(time / duration, 1); // get percent of completion in range [0, 1]
// apply the easing, it can cause bad-looking
// slow frames in browser performance tool, so be careful...
percent = easeInOutCubic(percent);
window.scrollTo(0, startingY + diff * percent);
// proceed with animation as long as we wanted it to.
if (time < duration) {
window.requestAnimationFrame(step)
}
})
}
document.getElementById('scrollMid').addEventListener('click', function(){
var element = document.getElementById('middle');
doScrolling(element, 1000);
});
I have an element which I animate to move across the screen. From left:-100px to left:screen-width. I loop this 4 times.
When returning the element back to its original position left:-100px, I don’t want it to be seen moving across the screen (from right to left) really fast.
I tried to do it by hiding the element with .hide() and then showing it after a while (so that it has time to move back to its initial position). But this doesn’t work:
$('.snake-image').hide();
$('.snake-image').css('top', height / 2).css('left', currentPos);
setTimeout(function(){$('.snake-image').show();},1000);
Code:
$('body').append('<a href="#"><img src="https://dl.dropboxusercontent.com/u/48552248/projects/covve/website/2015/public/images/snake.png" class="snake-image" style="position:absolute;top:0;" />');
function goRight(currentPos) {
$('.snake-image').animate({
left: currentPos
}, 100);
}
function moveSnake() {
while (currentPos <= width) {
goRight(currentPos);
currentPos += 20;
console.log(width + " x " + currentPos);
}
}
var currentPos,
height = $(window).height(),
width = $(window).width(),
i = 4;
var intervalID = setInterval(function(){
if (i > 0){
currentPos = -100;
$('.snake-image').hide();
$('.snake-image').css('top', height / 2).css('left', currentPos);
setTimeout(function(){$('.snake-image').show();},1000);
moveSnake();
i--;
console.log('Interval 1');
} else {
clearInterval(intervalID);
}
}, 100);
Demo: http://jsfiddle.net/m0epjLym/
you could use the animate callback
triggered at the end of the animation, you can move your item back in the origina position and then call again the animation
Fiddle:http://jsfiddle.net/xgknu376/
You can do this:
$('.snake-image').animate({'opacity': 0}, 0);
$('.snake-image').animate({'top': height / 2}, 0).animate({'left': currentPos}, 0).delay(1000).animate({'opacity': 1}, 0);
The delay function will only work on items that are in the animation queue.
Fiddle: http://jsfiddle.net/y995cts3/3/
I use chrome and scrolling is fast but its dont smooth. Text jumps multiple times.
But on this site http://www.if-not-true-then-false.com/ scroll works very smooth! And FAST!
http://bassta.bg/demos/smooth-page-scroll/ This scroll is smooth but very sloow and lagga (fast mount wheel dont change speed of scroll screen)
How this site have this smooth scroll? I cant find it(
try this one
<script type="text/javascript">
if (window.addEventListener) window.addEventListener('DOMMouseScroll', wheel, false);
window.onmousewheel = document.onmousewheel = wheel;
function wheel(event) {
var delta = 0;
if (event.wheelDelta) delta = event.wheelDelta / 120;
else if (event.detail) delta = -event.detail / 3;
handle(delta);
if (event.preventDefault) event.preventDefault();
event.returnValue = false;
}
function handle(delta) {
var time = 1000;
var distance = 300;
$('html, body').stop().animate({
scrollTop: $(window).scrollTop() - (distance * delta)
}, time );
}
</script>
First make a link with #top link then try the following code
try this
<script type="text/javascript">
$("a[href='#top']").click(function() {
$("html, body").animate({ scrollTop: 0 }, 1000);//here you can specify your time for smooth operation
return false;
});
</script>
I have a JS to make a smooth scroll from the bottom of the page to the top with this and it works:
<script>
$("a[href='#top']").click(function() {
$("html, body").animate({ scrollTop: 0 }, "slow");
return true;
});
</script>
But now I want to make a smooth scroll from the top to the bottom, I tried it with this:
<script>
$("a[href='#footer']").click(function() {
$("html, body").animate({ scrollToBottom: 0 }, "slow");
return true;
});
</script>`
It doesn't work, it's not a smooth scroll. Does anyone know what's wrong with this?
With pure JS:
window.scrollTo({ top: document.body.scrollHeight, behavior: 'smooth' })
and to the top as:
window.scrollTo({ top: 0, behavior: 'smooth' })
There is no such thing as scrollToBottom. Try this:
$("html, body").animate({ scrollTop: document.body.scrollHeight }, "slow");
For a more comprehensive list of methods for smooth scrolling, see my answer here.
To scroll to the bottom of the page, the y-position can be set to document.scrollingElement.scrollHeight.
For scrolling to a certain position in an exact amount of time, window.requestAnimationFrame can be put to use, calculating the appropriate current position each time. setTimeout can be used to a similar effect when requestAnimationFrame is not supported.
/*
#param pos: the y-position to scroll to (in pixels)
#param time: the exact amount of time the scrolling will take (in milliseconds)
*/
function scrollToSmoothly(pos, time) {
var currentPos = window.pageYOffset;
var start = null;
if(time == null) time = 500;
pos = +pos, time = +time;
window.requestAnimationFrame(function step(currentTime) {
start = !start ? currentTime : start;
var progress = currentTime - start;
if (currentPos < pos) {
window.scrollTo(0, ((pos - currentPos) * progress / time) + currentPos);
} else {
window.scrollTo(0, currentPos - ((currentPos - pos) * progress / time));
}
if (progress < time) {
window.requestAnimationFrame(step);
} else {
window.scrollTo(0, pos);
}
});
}
function scrollToSmoothly(pos, time) {
var currentPos = window.pageYOffset;
var start = null;
if(time == null) time = 500;
pos = +pos, time = +time;
window.requestAnimationFrame(function step(currentTime) {
start = !start ? currentTime : start;
var progress = currentTime - start;
if (currentPos < pos) {
window.scrollTo(0, ((pos - currentPos) * progress / time) + currentPos);
} else {
window.scrollTo(0, currentPos - ((currentPos - pos) * progress / time));
}
if (progress < time) {
window.requestAnimationFrame(step);
} else {
window.scrollTo(0, pos);
}
});
}
document.querySelector('button').addEventListener('click', function(e){
scrollToSmoothly(document.scrollingElement.scrollHeight, 1000);
});
html, body {
height: 5000px;
}
<button>Scroll to bottom</button>
The SmoothScroll.js library can be used as well, which handles more complex cases such as smooth scrolling both vertically and horizontally, scrolling inside other container elements, different easing behaviors, scrolling relatively from the current position, and more.
smoothScroll({yPos: 'end', duration: 1000});
document.querySelector('button').addEventListener('click', function(e){
smoothScroll({yPos: 'end', duration: 1000});
});
html, body {
height: 5000px;
}
<script src="https://cdn.jsdelivr.net/gh/LieutenantPeacock/SmoothScroll#1.2.0/src/smoothscroll.min.js" integrity="sha384-UdJHYJK9eDBy7vML0TvJGlCpvrJhCuOPGTc7tHbA+jHEgCgjWpPbmMvmd/2bzdXU" crossorigin="anonymous"></script>
<button>Scroll to bottom</button>
// Scroll smoothly to the bottom
domElement.scrollTo({
top: document.body.scrollHeight,
behavior: 'smooth',
})
All options for scrollTo are:
top: number
left: number
behavior: 'smooth' or behavior: 'auto'
The accepted answer and others are correct, but wanted to add another usecase that might help someone.
In some cases, you'd need to do the scrolling inside a setTimeout()'s callback with a short delay.
function scrollToBottom() {
window.scrollTo({ top: document.body.scrollHeight, behavior: 'smooth' });
}
setTimeout(function() { scrollToBottom(); }, 100);
For example: you have a <button> which adds a <div> element to the bottom of the page when clicked on, and you want to scroll to the bottom so the user can see this new div. In this case, sometimes (depends on the event-loop behavior), you'd need to do the scroll inside a setTimeout() because the same action that triggers the scroll actually changes the value of document.body.scrollHeight. By delaying it, you make it use the new updated value of document.body.scrollHeight after the div was added.
I have problem with this sprite animation.
sprite-sheet
The script don't change the correct animation, and the speed increases each time you click in the same direction.
<div id="coordinates">MOUSE XY</div>
<div id="map" style="width:960px; height:80px; background-color:black; ">
<div id="player"></div>
</div>
Javascript and Jquery
<style> #player{background-image:url('girl_60x60.png');
width:60px; height:60px; position:relative;
z-index:12; left:465px;}</style>
<script type="text/javascript">
// click event
$('#map').click(function(e) {
// take coordinates
var posX = e.pageX ;
var posY = e.pageY;
//print X e Y
$('#coordinates').html("X: " + posX + " Y: " + posY);
if (posX <= 480) { //Check the click relative to the center.
setInterval('ani_left()',100); //left animation
} else {
setInterval('ani_right()',100); //right animation
}
});
var frame = 1;
// Right animation
function ani_right() {
var left = 60 * frame; //next frame every 60px
var top = 0;
$('#player').css('backgroundPosition','-'+left+'px -'+top+'px');
frame++;
}
// left animation
function ani_left() {
var left = 60 * frame;
var top = 60; //second row of frames
$('#player').css('backgroundPosition','-'+left+'px -'+top+'px');
frame++;
}
</script>
You should stop the execution of previous setInterval with clearInterval(idInterval).
I reccomend you to use setInterval(funcName,100) and not setInterval('funcName()',100);
var idInt = -1; // add this
// click event
$('#map').click(function(e) {
if(idInt != -1)
clearInterval(idInt); // add this
/* .. CUT .. */
if (posX <= 480) { //Check the click relative to the center.
idInt = setInterval(ani_left,100); //left animation
} else {
idInt = setInterval(ani_right,100); //right animation
}
});
/* cut */
Fiddle here
You have to clear your old draw interval before you start a new one
var interval;
if (posX <= 480) { //Check the click relative to the center.
clearInterval(interval);
interval = 0;
interval = setInterval(ani_left,100); //left animation
} else {
clearInterval(interval);
interval = 0;
interval = setInterval(ani_right,100); //right animation
}