javascript or mootools way to animate scrollTop like jQuery - javascript

What is the equivalent of this:
$('html, body').animate({
scrollTop: 200
}, 400);
In MooTools or agnostic javascript?
Im going round in circles....
Cheers

This loop can animate the scrollTop property of the window in basic javascript:
window.onload = function() {
var offset = 0; //vertical offset
var interval = setInterval(function() {
window.scrollTo(0, offset);
offset += 4; // plus 4 pixels
if (offset >= 200) {
clearInterval(interval);
}
}, 8); // 200px/4px==50 cycles ; 400ms/50cycles == 8ms per cycle
};
fiddle

Because you asked for a version in mootools, it's just one line:
new Fx.Scroll(window).start(0, 200);​
http://jsfiddle.net/ye3vX/
Note: It needs mootools more's Fx.Scroll.

Related

How to control the speed of js nav scrolling

Hey Guys I found this really useful java script sticky side nav, and it works great! I don't much about js, i was just wondering if there was away to slow down the scrolling?
function redrawDotNav(){
var topNavHeight = 50;
var numDivs = $('section').length;
$('#dotNav li a').removeClass('active').parent('li').removeClass('active');
$('section').each(function(i,item){
var ele = $(item), nextTop;
console.log(ele.next().html());
if (typeof ele.next().offset() != "undefined") {
nextTop = ele.next().offset().top;
}
else {
nextTop = $(document).height();
}
if (ele.offset() !== null) {
thisTop = ele.offset().top - ((nextTop - ele.offset().top) / numDivs);
}
else {
thisTop = 0;
}
var docTop = $(document).scrollTop()+topNavHeight;
if(docTop >= thisTop && (docTop < nextTop)){
$('#dotNav li').eq(i).addClass('active');
}
});
}
$('#dotNav li').click(function(){
var id = $(this).find('a').attr("href"),
posi,
ele,
padding = $('.navbar-fixed-top').height();
ele = $(id);
posi = ($(ele).offset()||0).top - padding;
$('html, body').animate({scrollTop:posi}, 'slow');
return false;
});
demo
The line in your JavaScript code doing that is this:
$('html, body').animate({scrollTop:posi}, 'slow');
You can change the 'slow', to 'fast', and see the difference.
Learn more about the animate function here.
You can precisely control the speed on animate with duration. Here is the function signature:
animate(params, [duration], [easing], [callback])
The strings fast and slow can be supplied to indicate durations of 200ms and 600ms, respectively. The default speed is 400ms. You can adjust your speed by replacing nnn with the exact speed in milliseconds you want.
$('html, body').animate({scrollTop:posi}, nnn);

Adapt scrollTop to work with different resolutions

This is what I use to make 2 divs "unwrap" while scrolling:
CSS
.entry {
height: 40px;
}
.entry.expanded {
height:600px;
}
JavaScript
$($('.entry').get(0)).addClass('expanded');
$(window).on('scroll', function (e) {
var x = $(window).scrollTop();
if (x > 820) {
$($('.entry').get(1)).addClass('expanded');
}
if (x > 1525) {
$($('.entry').get(2)).addClass('expanded');
}
});
It works perfectly fine on my 1920x1080p screen but it doesn't on a friend's 1920x1200px because there aren't 820px to scroll..
How can I solve this to work with every resolution? I tried with this, but unfortunately nothing happens:
$($('.entry').get(0)).addClass('expanded');
$(window).on('scroll', function (e) {
var availableScroll = $(document).height() - $window.height();
var x = $(window).scrollTop();
if (x > 820 || x == availableScroll) {
$($('.entry').get(1)).addClass('expanded');
}
if (x > 1525 || x == availableScroll) {
$($('.entry').get(2)).addClass('expanded');
}
});
Is there a fancy method, that maybe calculates the pixels from the bottom or some method relative to the vertical res?
Here's the webpage with the code live (you can see the 2 divs unwrapping when scrolling).
In general, avoid the == for scrolling because if the scroll is off by even .0001 it will resolve as false. Also replace $window with $(window).
$($('.entry').get(0)).addClass('expanded');
$(window).on('scroll', function (e) {
var availableScroll = $(document).height() - $(window).height();
var x = $(window).scrollTop();
if (x > 820 || Math.abs(x - availableScroll) < 10) {
$($('.entry').get(1)).addClass('expanded');
}
if (x > 1525 || Math.abs(x - availableScroll) < 10) {
$($('.entry').get(2)).addClass('expanded');
}
});
Also, if you want to execute code when the page first loads, use the $(document).ready(handler) pattern.
Your former functions seems to working fine. I am testing it as MacBook Pro. However, at sometime it seems it is not fired at JQuery. What you can do is you can wait for few milliseconds to check if the scroll is finished. If scroll is finished then you can simply check the value of scroll.
Option 1:
jQuery debounce is a nice one for problems like this. jsFidlle
So your modified code will be (you need to use debounce)
$(window).scroll($.debounce( 250, true, function(){
console.log("Still scrolling");
}));
$(window).scroll($.debounce( 250, function(){
var x = $(window).scrollTop();
console.log("Scrolling finished");
if (x > 820) {
$($('.entry').get(1)).addClass('expanded');
}
if (x > 1525) {
$($('.entry').get(2)).addClass('expanded');
}
}));
Option 2:
There may be a chance you don't like use JQuery Debounce then you can native approach with timer function. See the code below and you can adjust the timer duration as per your needs.
It is simply waiting for scroll event to be finished and wait for certain milliseconds before it scroll event recalled. If scroll refires then it simply clear the timer and start waiting again. If timer is finished then it executes the method you have stated.
$(window).scroll(function() {
var timerDuration = 250; // In milliseconds
clearTimeout($.data(this, 'scrollTimer'));
$.data(this, 'scrollTimer', setTimeout(function() {
// do something
var x = $(window).scrollTop();
console.log("Scrolling finished");
if (x > 820) {
$($('.entry').get(1)).addClass('expanded');
}
if (x > 1525) {
$($('.entry').get(2)).addClass('expanded');
}
}, timerDuration));
});

Using lodash updatePosition not working

Hello So I am using lodash for the first time. My jquery code keeps jumping and I am trying to migrate it in the lodash function but I don't really understand how.
IDK if this matter but the main idea behind the code is for a div to scroll down to a position and snap to place but it keeps jumping. please advise !!
$(window).on('scroll', _.throttle(updatePosition, 100));
$(window).on('scroll', function(){
var scroll = $(window).scrollTop();
var sectionPosTop = document.getElementById('header-bamboo-scroll').getBoundingClientRect();
var headerHeight = document.getElementById('header').getBoundingClientRect();
if (scroll >= 660 && scroll <= 680 ) {
console.log('greater than 660 and less than 680');
$('html, body').animate({
scrollTop: headerHeight.height
}, 500, function() {
$('html, body').stop();
});
}
});
});
I don't understand exactly what you want to do, but you can to use _.throttle to get a delay between code execution and that can give you a smooth animation. You can to adjust the delay time (in milliseconds) to get what you want.
var updatePosition = function() {
var scroll = $(window).scrollTop();
var sectionPosTop = document.getElementById('header-bamboo-scroll').getBoundingClientRect();
var headerHeight = document.getElementById('header').getBoundingClientRect();
if (scroll >= 660 && scroll <= 680 ) {
console.log('greater than 660 and less than 680');
$('html, body').animate({
scrollTop: headerHeight.height
}, 500, function() {
$('html, body').stop();
});
}
}
$(window).on('scroll', _.throttle(updatePosition, 100));

Lightweight scrollUp function - jQuery

Trying to make simple jQuery function to create a scrollToTop button that fades in as you scroll down.
$(document).ready(function() {
var start = 300;
var duration = 200;
var scrolled;
$('.scrollUp').css('opacity', '0.0');
$(window).scroll(function(){
var opacity = (scrolled - start) / duration;
scrolled = $(window).scrollTop();
if (0 < opacity < 1) {
$('.scrollUp').css('display', 'block').css('opacity', opacity);
} else if (1 < opacity) {
$('.scrollUp').css('display', 'block').css('opacity', '1.0');
} else {
$('.scrollUp').css('display', 'none').css('opacity', '0.0');
}
});
$('.scrollUp').click(function(){
$('html, body').animate({
scrollTop: 0
}, 500);
});
});
See it in action here: http://jsfiddle.net/JamesKyle/fBvGH/
This works, tested in jsfiddle:
$(document).ready(function() {
var start = 300;
var duration = 200;
var scrolled;
$('.scrollUp').css('opacity', '0.0');
$(window).scroll(function(){
var opacity = (scrolled - start) / duration;
scrolled = $(window).scrollTop();
if (0 < opacity < 1) {
$('.scrollUp').css('display', 'block').css('opacity', opacity);
} else if (1 < opacity) {
$('.scrollUp').css('display', 'block').css('opacity', '1.0');
} else {
$('.scrollUp').css('display', 'none').css('opacity', '0.0');
}
});
$('.scrollUp').click(function(){
$('html,body').animate({
scrollTop: 0
}, 500);
});
});
Update:
And here's a working example with the opacity animation.
Looks like this guy was looking for the same equation.
Better to use some math in situation's like this:
scrolled = $(window).scrollTop();
height = $('body').height();
height = Math.ceil((scrolled / height) * 100);
height = height / 100;
Second Update
Ok, you want it to start appearing after the dark blue section. Ok, so what you need to do is exclude that portion of the top before the gradient. You can do that by making an if clause that checks if the scrollTop value has hit the top part of the light blue gradient; around 300px from the top of the document. Then instead of using the body height in the above equation, use the total height of the gradient section; about 210px. This value will replace the var height in the jQuery above. Let me know if you have issues implementing this. Didn't notice you're comment on the above answer.
scrollTop is not a window property, so just change you code slightly:
$(window).animate({scrollTop : 0},500);
to
$('html, body').animate({scrollTop : 0},500);
here's the updated jsfiddle: http://jsfiddle.net/fBvGH/13/

Javascript: Scroll to nth row in a table?

Using either pure Javascript or jQuery, how do I scroll the page so that the nth row in a table is centered on the page?
Some examples I've seen that have this sort of feature usually require that the element I scroll to uses an id as the selector, but since the table has a dynamic amount of rows and may be paged, I'd rather not go this route of having to give each <td> tag an id.
Is the easiest way to just calculate the position of the td relative to the top of the document and scroll the window using setInterval until the middle of the window is >= to the position of the nth <td> tag?
I suppose some pseudo-code of the way I imagine it working would be:
function scrollToNthTD(i) {
var position = CalculatePositionOfTR(i);
var timer = setTimeout(function () {
ScrollDownALittle();
if( CenterOfVerticalWindowPosition > position)
clearInterval(timer);
}, 100);
}
Latest update (no-jquery for for modern browsers)
var rows = document.querySelectorAll('#tableid tr');
// line is zero-based
// line is the row number that you want to see into view after scroll
rows[line].scrollIntoView({
behavior: 'smooth',
block: 'center'
});
Demo at http://jsfiddle.net/r753v2ky/
Since you can use jQuery here it is..
var w = $(window);
var row = $('#tableid').find('tr').eq( line );
if (row.length){
w.scrollTop( row.offset().top - (w.height()/2) );
}
Demo at http://jsfiddle.net/SZKJh/
If you want it to animate instead of just going there use
var w = $(window);
var row = $('#tableid').find('tr').eq( line );
if (row.length){
$('html,body').animate({scrollTop: row.offset().top - (w.height()/2)}, 1000 );
}
Demo at http://jsfiddle.net/SZKJh/1/
Don't use jQuery - it slows down sites!
var elem = document.getElementById("elem_id");
elem.scrollIntoView(true);
You can do something like this
function CalculatePositionOfTR(){
return $('tr:eq(' + i + ')').offset().top;
}
function ScrollDownALittle(position){
$('html, body').animate({
scrollTop: position
}, 2000);
}
function scrollToNthTD(i) {
var position = CalculatePositionOfTD(i);
var timer = setTimeout(function () {
ScrollDownALittle(position);
if( CenterOfVerticalWindowPosition > position)
clearInterval(timer);
}, 100);
}
Give this a shot:
/*pseudo-code*/
$("td.class").bind("click", function() {
var y = $(this).position().top,
h = $(window).height();
if(y > h/2) {
$("body").animate({
scrollTop: y - h/2
}, 2000);
};
});
aka-g-petrioli
I have corrected the followings from your answer.
$('#control button').click(function(){
var w = $(window);
var row = table.find('tr')
.removeClass('active')
.eq( +$('#line').val() )
.addClass('active');
if (row.length){
w.scrollTop( row.offset().top - row.offset().top/5);
}
});
This will help you to scroll accurate position.

Categories