ScrollTop when scroll is detected - javascript

I want to make a feature like the one on this page. B&O BeoPlay A3
When you scroll down it automatically scrolls all the way to the next page.
I have been playing around with window.pageYOffset.
I have this so far:
window.onscroll = scroll;
function scroll () {
setTimeout(function() {
if (window.pageYOffset < 100 && window.pageYOffset > 2) {
scrollLogin();
}
else if (window.pageYOffset > 100 && window.pageYOffset < 159 && window.pageYOffset != 124) {
scrollSky();
}
else if (window.pageYOffset > 159 && window.pageYOffset < 248) {
scrollCity();
}
},500);
}
function scrollLogin() {
$('html,body').animate({
scrollTop: $("#login").offset().top
}, 500);
}
function scrollSky() {
$('html,body').animate({
scrollTop: $("#skyContainer").offset().top
}, 500);
}
function scrollCity() {
$('html,body').animate({
scrollTop: $("#city").offset().top
}, 500);
}
The problem is that this way is not working seamless at all. I have to wait 500ms until I scroll again. And if this also only works with a fixed screen resolution.
Do you know a better way do archive this feature? That also allows percentage measures so that it works on different resolution monitors?
Link to my attempt.
So I want 3 states that the viewport sticks to: top (the login bar), middle (the sky animation) and bottom (the search bar).
Thank you very much!
EDIT:
TAKE 2:
I made a variable that tells me if the animation is ended. It is simply has the value as '1' while the animation is on, this prevents all sorts of chaos.
So I have the script working pretty well now. The only catch is that it only works with exactly my innerHeight and innerWidth. (innerHeight: 863 - innerWidth: 1440).
Is there a way to make window.pageYOffset in percentages?
And is this the best way to archive this effect?
Thank you, have a nice day.
This is my new code:
window.onscroll = scroll;
var animationIsOn = 0;
function scroll () {
if (animationIsOn == 0) {
var pageY = window.pageYOffset;
if (pageY < 119 && pageY > 69) {
scrollLogin();
}
else if (pageY > 5 && pageY < 69 || pageY > 179 && pageY < 254) {
scrollSky();
}
else if (pageY > 129 && pageY < 179) {
scrollCity();
}
}
}
function scrollLogin() {
animationIsOn = 1;
$('html,body').animate({
scrollTop: $("#login").offset().top
}, 500, function() {
animationIsOn = 0;
});
}
function scrollSky() {
animationIsOn = 1;
$('html,body').animate({
scrollTop: $("#skyContainer").offset().top
}, 500, function() {
animationIsOn = 0;
});
}
function scrollCity() {
animationIsOn = 1;
$('html,body').animate({
scrollTop: $("#city").offset().top-600
}, 500, function() {
animationIsOn = 0;
});
}

To get pageYOffset as a percentage, simply divide pageYOffset by document.documentElement.scrollHeight and multiply by a 100.
EDIT: Ckrill has found that he needed to use window.innerHeight and not the document's scrollHeight property.

Related

vertical slider on scroll

i am searching for a slider which should change the slides vertically on scroll.
This is the refrence Url : https://www.uber.com/ The Mobile slider
Please help me,i am trying to do this since7,8 hours.
this is the code i am trying to use.
$(document).ready(function() {
// var totalheight=$(window).height();
// $('.carosel-section').css('height',totalheight);
//Set each section's height equals to the window height
//$('.moveable').height($(window).height());
$('.moveable').first().addClass('active');
$('.carousel-wrap').on('mousewheel DOMMouseScroll', function (e) {
e.preventDefault();//prevent the default mousewheel scrolling
var active = $('.moveable.active');
var delta = e.originalEvent.detail < 0 || e.originalEvent.wheelDelta > 0 ? 1 : -1;
if (delta < 0) {
//mousewheel down handler
next = active.next();
if (next.length) {
var timer = setTimeout(function () {
$('body, html').animate({
scrollTop: next.offset().top
}, 'fast');
// move the indicator 'active' class
next.addClass('active')
.siblings().removeClass('active');
clearTimeout(timer);
}, 100);
}
} else {
prev = active.prev();
if (prev.length) {
var timer = setTimeout(function () {
$('body, html').animate({
scrollTop: prev.offset().top
}, 'slow');
prev.addClass('active')
.siblings().removeClass('active');
clearTimeout(timer);
}, 800);
}
}
});
});
Have you tried looking at Parallax.js? I think that is what you are looking for. The examples on the main page should give you a quick start!

jquery animate is very buggy

I am using JQuery animate to animate an image down when scrolled 100 or more pixels. Then when I scroll back to the top it needs to go back in original state. Instead of that on the way back it just goes up and down all over again until it finaly stops.
How can I fix that?
$(document).ready(function() {
$(window).scroll(function() {
if ($(this).scrollTop() >= 100) {
//alert('scrolled');
$('.flipje_pas_image').animate({
top: -50
}, 1000);
}
if ($(this).scrollTop() < 100) {
$('.flipje_pas_image').animate({
top: -450
}, 1000);
}
});
});
you need to use a a boolean state that flips when the if condition is met that makes the animation happen once instead eavery scroll event
like this
$(document).ready(function() {
var once = false;
$(window).scroll(function() {
if ($(this).scrollTop() >= 100) {
//alert('scrolled');
if(!once){
once = true
console.log('ssd' , once)
$('.flipje_pas_imag').animate({
top: -50
}, 1000);
}
}
if ($(this).scrollTop() < 100) {
if(once){
once = false;
$('.flipje_pas_imag').animate({
top: -450
}, 1000);
}
}
});
});

Sticky Tabs Attaching To Specific Div

Ok so I have some sticky tabs that I am using to automatically pin to the top of the content area when scrolling so the user always knows that category they are in. You can see this here http://www.codeclimb.com/menus3/index2.html as you scroll the tab will stick the top. I am achieving this with the following javascript
function stickyTitles(stickies) {
this.load = function() {
stickies.each(function(){
var thisSticky = jQuery(this).wrap('<div class="followWrap" />');
thisSticky.parent().height(thisSticky.outerHeight());
jQuery.data(thisSticky[0], 'pos', thisSticky.offset().top);
});
}
this.scroll = function() {
stickies.each(function(i){
var thisSticky = jQuery(this),
nextSticky = stickies.eq(i+1),
prevSticky = stickies.eq(i-1),
pos = jQuery.data(thisSticky[0], 'pos');
if (pos <= jQuery(window).scrollTop()) {
thisSticky.addClass("fixed");
if (nextSticky.length > 0 && thisSticky.offset().top >= jQuery.data(nextSticky[0], 'pos') - thisSticky.outerHeight()) {
thisSticky.addClass("absolute").css("top", jQuery.data(nextSticky[0], 'pos') - thisSticky.outerHeight());
}
} else {
thisSticky.removeClass("fixed");
if (prevSticky.length > 0 && jQuery(window).scrollTop() <= jQuery.data(thisSticky[0], 'pos') - prevSticky.outerHeight()) {
prevSticky.removeClass("absolute").removeAttr("style");
}
}
});
}
}
jQuery(document).ready(function(){
var newStickies = new stickyTitles(jQuery(".followMeBar"));
newStickies.load();
jQuery(window).on("scroll", function() {
newStickies.scroll();
});
});
However you can see that this is designed to stick the tabs to the very top of the browser and not right below the header. Currently I have applied a margin-top to the CSS to make the followbar stick to the bottom of the div I want it to (the "now serving" section) but you can see that it takes longer for the title tab to snap to the next category because it is really doing it when it hits the top of the browser.
So as each time it passes the "now serving" section I want it to snap the tab there.
Any fix on how I can make it work to the div I want specifically?
You can accomplish this by accounting for the height of the header in the $(window).scroll event like so:
this.scroll = function() {
stickies.each(function(i){
var thisSticky = jQuery(this),
nextSticky = stickies.eq(i+1),
prevSticky = stickies.eq(i-1),
pos = jQuery.data(thisSticky[0], 'pos');
if (pos - 120 <= jQuery(window).scrollTop()) {
//**120px is the height of the header
thisSticky.addClass("fixed");
if (nextSticky.length > 0 && thisSticky.offset().top - 120 >= jQuery.data(nextSticky[0], 'pos') - thisSticky.outerHeight()) {
thisSticky.addClass("absolute").css("top", jQuery.data(nextSticky[0], 'pos') - thisSticky.outerHeight() - 120);
}
} else {
thisSticky.removeClass("fixed");
if (prevSticky.length > 0 && jQuery(window).scrollTop() <= jQuery.data(thisSticky[0], 'pos') - prevSticky.outerHeight()) {
prevSticky.removeClass("absolute").removeAttr("style");
}
}
});
}
P.S. When can I buy a chicken kabob drink? :)
I would change the line:
if (pos <= jQuery(window).scrollTop())
To something like this:
if (pos <= jQuery(window).scrollTop() + offset)
Where offset is equal to the height of the header.

trigger a jquery effect when you scroll

Hey guys I'm back with another question. I'm using the code below to add a bouncing effect to a div on my site. It works fine right now but the div has to be clicked in order for the effect to start. I would like to modify it so that when the user is scrolling down the page and reaches that section it triggers the effect automatically. How can I modify the code below to trigger the effect when the user scroll's down and reaches that section of the site?
Here is the code I' using
$(".servi-block").click(function () {
doBounce($(this), 2, '10px', 150);
});
function doBounce(element, times, distance, speed) {
for (i = 0; i < times; i++) {
element.animate({
marginTop: '-=' + distance
}, speed)
.animate({
marginTop: '+=' + distance
}, speed);
}
}
$(window).scroll(function(event){
isElementVisible = inViewport($(".servi-block"));
if(isElementVisible)
{
doBounce($(this), 2, '10px', 150);
}
});
function inViewport (el)
{
var r, html;
if ( !el || 1 !== el.nodeType ) { return false; }
html = document.documentElement;
r = el.getBoundingClientRect();
return ( !!r
&& r.bottom >= 0
&& r.right >= 0
&& r.top <= html.clientHeight
&& r.left <= html.clientWidth
);
}
This should help you out: http://api.jquery.com/scroll/
$( "#target" ).scroll(function() {
$( "#log" ).append( "<div>Handler for .scroll() called.</div>" );
});
Also utilize this
$('#target').on("mousewheel", function() {
alert($(document).scrollTop());
});
Those two together should get you the ability to figure out you are scrolling, and when you reach position X, do something.
EDITED
Let's go at it this way -
var targetPos = "500px";
$( document ).scroll(function() {
if ($(document).scrollTop() == targetPos) {
doBounce($(this), 2, '10px', 150);
}
});
You can simply check to see when the element comes into view by taking the element's offset and subtracting that element's parent height and scrollTop value.
Here's an example:
$(document).ready(function() {
$(document).on('scroll', function() {
var offset = $('.element').offset().top,
scroll = $(document).scrollTop(),
height = $(document).height(),
inViewDown = ((offset - scroll - height) <= 0) ? true : false;
if (inViewDown) {
// Do some stuff
}
});
});
Here's a working example: http://jsfiddle.net/ughEe/

Force "overscrolling" at Chrome/Mac with javascript

When you get to the limit of document, you can keep scrolling and can see an background behing the document before it bounces back (overscrolling).
How can I force the window to overscroll like this with javascript?
This is not the ultimate solution since I think the animation is imperfect and it's really only for desktops, but it can at least get you started. What I have done is increase the height of the body for animation on scroll.
$(document).on('scroll mousewheel', function (e) {
//Check for mousewheel scrolling down (or not used at all)
if (!e.originalEvent || !e.originalEvent.wheelDeltaY
|| e.originalEvent.wheelDeltaY < 0) {
if ($(window).height() + $(this).scrollTop() == $(this).height()) {
//Prevent simultaneous triggering of the animation
if (!$("body").data('bouncing')) {
$("body").height(function (_, h) { return h + 15; })
.data('bouncing', true);
$("body, html").animate({
'scrollTop': '+=15'
}, 125).animate({
'scrollTop': '-=15'
}, {duration: 125, complete: function () {
$(this).height(function (_, h) { return h - 15; })
.data('bouncing', false);
}});
}
}
}
}).on('keydown', function (e) {
//The "down" arrow; still bounces when pressed at the bottom of the page
if (e.which == '40') {
$(this).trigger('scroll');
}
});
I've been playing with this version that imitates the effect using a div, that slides in and out of view at the bottom of the page. If you have a high res monitor, you may need to increase the height of the main div to test it.
<div id="main" style="background:#f5f5f5;height:1000px"></div>
<div id="overscroll" style="background:#666666;height:120px"></div>
<script type="text/javascript">
var $doc = $(document);
$doc.ready(function () {
var $wnd = $(window),
$oscroll = $('#overscroll'),
block = false;
$wnd.bind('scroll', function () {
if (!block) {
block = true;
var scrollTop = $wnd.scrollTop(),
wndHeight = $wnd.height(),
docHeight = $doc.height();
try {
if (scrollTop + (wndHeight + 120) > docHeight) {
$oscroll.slideUp('slow');
}
else if ($oscroll.css('display') === 'none'
&& (scrollTop + (wndHeight + 120) < docHeight)) {
$oscroll.slideDown();
}
} finally {
block = false;
}
}
});
});
</script>

Categories

Resources