jQuery/JS – scroll to next element on click (scrollable div issues) - javascript

I have a simple blog, and each blog post has a number of images ranging from 1 to 10. If you click on any of the images in the post, it should scroll you down to the next post. I thought something as simple as this would've worked:
$('.each-journal-entry .slider-container .journal-slider .each-slide img').on('click', function () {
var $this = $(this);
$('.journal-container').animate({
scrollTop: $this.closest('.each-journal-entry').next().offset().top
}, 500);
});
But when I click another image, except for the first one, it just scrolls to an odd position.
I managed to achieve this with some help, and you can see the output here: http://jsfiddle.net/w7rtcmp0/3/ which works great, but the difference for me is that my content is in a scrollable div (hence .journal-container and not html, body.
Any ideas why I am having this issue? I have created a jsFiddle with the scrollable div, and if you click an image further down... it replicates this issue... so hopefully this helps.
http://jsfiddle.net/w7rtcmp0/5/
Thanks.

jQuery adjusts offset().top() based on the current scroll position.
Using JavaScript's offsetTop property should fix the problem:
scrollTop: $this.closest('.each-journal-entry').next()[0].offsetTop
Fiddle: http://jsfiddle.net/m7cm5oL6/

So I think you were trying to use the wrong height.
Here I set a variable of height and set it to the height of the current journal/blog object. This allows me to scroll my height all the way down to the next available blog object.
http://jsfiddle.net/w7rtcmp0/24/
$('.each-journal-entry .slider-container .journal-slider .each-slide img').on('click', function() {
$this = $(this);
var height = $this.closest('.each-journal-entry').height();
$('.scrollable').animate({
scrollTop: height
}, 2000);
});

You may want to look at Ariel Flesler's jQuery scrollTo plugin, I had the same issue and using this saved me hours of debugging.

Related

JQuery .scrollTop() and .offset().top issue: how it work? How to solve?

I want to achieve some kind of smooth scrolling, so I made this script:
$('a').click(function(){
var sclink = $(this).attr('href');
$('.menu').animate({
scrollTop: $(sclink).offset().top
}, 500);
return false;
});
The problem? When I click on the 'a' the offset.top() value changes in another weird value and toggle between them? Why does this happen and how do I resolve it?
http://jsfiddle.net/StartStep/9SDLw/2947/
I think the problem is with the scroll.top() that gets the value in another way...
jsfiddle.net/9SDLw/2950/
$('a').click(function(){
var sclink = $(this).attr('href');
$('.menu').animate({
scrollTop: $(sclink).position().top
}, 500);
logit('Anchor: '+sclink+'; Offset top value: <b>'+$(sclink).offset().top+'</b>')
return false;
});
Use position instead of offset.
The reason is offset is relative to the viewport, as such it looks like you've scrolled too far, but this is because the top of your viewport area is being obscured by your layout, so offset is actually not what you want, instead, position is.
You should also add a reference to stop before calling animate to ensure if a user clicks in quick succession the behaviour is as expected (the animation queue is essentially flushed)
With that in mind your HTML also needs some work- the clickable link hasnt got closing tags for example.
Change your scrolling code to:
$('.menu').stop(true,true).animate({
scrollTop: $(sclink).position().top
}, 500);
Demo Fiddle

Play through pinned elements in superscrollorama

I am building a Parallax website using SuperScrollorama which have some animation frame by frame using jquery and css3...
But after ending up doing so i am stuck in a problem, i am trying to navigate the pages using some scroll plugin...
I have tried Basic jquery using scrollTop event, using Jquery ScrollTo and using Tween Lite ScrollTo plugin to navigate through pages but nothing seems to work...
The issue i get after goggling it is if pages are pinned together as position:fixed; and pages doesnot scroll to that position and stuck between...
With Jquery ScrollTo, my code:-
$('.menus a').click(function(e){
e.preventDefault();
$.scrollTo(this.hash, 2000, {
easing:'easeInOutExpo',
offset:3000,
axis:'y',
queue:true
});
});
With basic scrollTop jquery, my code:-
$('a').bind('click',function(event){
var $anchor = $(this);
$('html, body').stop().animate({
scrollTop: $($anchor.attr('href')).offset().top
}, 1500,'easeInOutExpo');
event.preventDefault();
});
Currently my code works like this:- http://jsfiddle.net/tFPp3/6/
As you can see in my demo, the scroll stuck between before reaching the exact position through hash...
What is the solution if i have to play through the pinned elements in Superscrollorama?
You'll have to do 2 animations : one to reach the ancher offset and then, after superscrollorama added new element for animation and recalculate the document height, do the second animation to reach the correct key frame on that page (that you fixed at offset 3000 of that section).
$(function(){
var hashes = [];
$('.menus a').each(function(){
hashes.push(this.hash);
});
console.log('hashes:', hashes);
$('.menus a').click(function(e){
e.preventDefault();
var h = this.hash;
var pageTop = $(h).offset()['top'];
console.log('pageTop=',pageTop);
$.scrollTo( pageTop+1, 2000, {
easing:'easeInExpo',
axis:'y',
onAfter:function(){
setTimeout(function(){
console.log('hashes:', hashes);
var id = hashes.indexOf(h);
console.log('hashes['+(id+1)+']=', hashes[(id+1)]);
var nextPageTop = $(hashes[id+1]).offset()['top'];
console.log('nextPageTop=', nextPageTop);
var keyOffset = pageTop + 3000;
console.log('keyOffset=',keyOffset);
if(keyOffset < nextPageTop ){
$.scrollTo( keyOffset, 2000, {
easing:'easeOutExpo',
axis:'y'
});
}
},100);
}
});
});
});
Note that each section offset changes constantly so, before launching the second animation, we have to test that we are not scrolling till the next section again. We also need a little delay here to let superscrollorama make its sauce before testing respective offsets (saddly it doesn't seem to provide an event to do so).
I had the same issue as you. Here's how I went about fixing it....
First of all we know that Superscrollorama adds a spacer pin before your element, it sets the height of the element which defines how long the user has to scroll through a section (the duration)....So in theory all we have to do is add up all the pin heights that happen BEFORE the element you want to scroll to and then offset from the top of that element...
What I did was....
Find out what element you want to scroll to. Check how many supersrollorama-pin-spacers there are before that pin, work out the heights of all of the pins and then offset it to your initial scrollTo function.
pin = $('#pin-id').prev(); //find the spacer pin
prevPin = pin.prevAll('.superscrollorama-pin-spacer'); //find all the pins before this
heights = []; //create an array to store the pin heights
$.each(prevPin, function( index, value ) {
value = $(this).attr('height'); //get each height
heights.push(value); // push it to array
});
//use eval to join all the heights together
heights = eval(heights.join("+"));
Now we have the height so lets scroll to it.....
TweenMax.to($('html,body'),1, { scrollTop:heights, });
Good Luck! I hope this helps you.
I have had a similar issue and found that janpaepke on the superscrollorama project added an additional toggle to make this easier.
You can manually add the spacers so you don't need to make adjustments by setting the pushFollowers flag in your pin to false.
Example JS
controller.pin($('#pin-id'), 200, {
anim: new TimelineLite().append([TweenMax.fromTo( $('#pin-id'), 2, {css:{opacity: 1}}, {css:{opacity: 0}})]),
offset: 0,
pushFollowers: false
});
Example HTML
<div id="pin-id">
Bunch of Content
</div>
<div style="padding-top: 200px"></div>

Make element scroll slower (Parallax)

I have an element on my page absolutely positioned.
Im trying to write a snippet of jQuery to make that element scroll at a slower rate than the rest of the elements on the page.
I've written this so far but cannot seem to get it too work at all. Has anybody experience with this and if so would you care explaining?
$(document).ready(function() {
$window = $(window);
$('.twit-bird').css({
'top' : -($('window')/3)+"px"
});
});
I've also tried to add an anchor, a fixed div at the top of my window to work out the calcs from that with no luck...
also tried this
$(document).ready(function() {
// Cache the Window object
windowScroll = $(this).scrollTop();
$(window).scroll(function() {
$('.twit-bird').css({
'top' : -(windowScroll/3)+"px"
});
});
});
I can point you in the right direction. You need your $('.twit-bird').css() to get called every time the window is scrolled. Also you forgot .scrollTop(), and don't quote window (or, even better just use this) ...
$(window).scroll(function () {
$('.twit-bird').css({
'top' : -($(this).scrollTop()/3)+"px"
});
});
Here is a very very good tutorial for parallax scrolling. It made me understanding how it really works.

Scroll to an html element with a particular id in javascript or jquery

I have html elements with id's assigned. Now I want to scroll to those elements. I see jQuery has a scrollTop which takes an integer value.. How do I easily just make a particular html element with an id scroll to the top? Ideally, with nice and smooth animation.
A quick search showed many scrolling plugins... if a plugin is needed for the above functionality, what's the most popular one? I'm also using jquery-ui.
You could use something like this to scroll to #someElement when the page loads:
$(document).ready(function() {
$("html, body").animate({scrollTop: $("#someElement").offset().top}, 1000);
});
It simply animates the scrollTop property of the body element, and uses the top offset of some specific element as the position to scroll to. The animation lasts for 1000ms.
Note: it selects both html and body so it works across browsers. I'm not sure on the specifics, but some quick tests show that Chrome uses body, but Firefox and IE use html.
Here's a working example.
Consider the following snippet:
$('#myDiv').bind('click',function(){
var pos = $(this).offset().top,
scrollSpeed = 2;
for (var i = pos; i > 0; i=i-scrollSpeed) {
$(window).scrollTop(i);
}
});
It scrolling was binded to #myDiv element on click just for example. Code determines a position of #myDiv element, than calculates number of scroll steps (speed/smoothness). Than does jQuery .scrollTop() thing.

JQuery animated banner

So I previously asked a question about how to create a banner like the one shown here and I got a really good answer to start me off. I have been working on it since and I'm having a lot of problems getting the animation to slide back to it's original position.
Here is my animation: http://jsfiddle.net/43nCF/ (don't click the green block first)
Issue: After the first time you toggle a block, clicking another block will not move it to the left.
I also have some other minor issues which I would be grateful if someone helped me with.
How do I get the width and the moving of the blocks to animate simultaneously like in the banner animation I am trying to replicate?
How do I get the block to slide back to the original position instead of just kind of 'transporting' there?
I am only beginner at jQuery so any help would be amazing.Thanks.
As for the positioning problem: you need to drop the left declaration in your second function.
Regarding making the animation act simultanous: animate both the right and the width property for each element, in one call:
function() {
var position = $.data(this, 'position');
var ind = $(this).index();
//moves image back to original position
$('#container div').each(
function() {
$(this).animate({
right: "",
width: 100
});
});
});
Working example here.
I see you have a response.
In case this version is of any help to you:
http://jsfiddle.net/vCbcz/
Instead of altering the divs other than the one being affected, I wrapped them all in a #slider div and adjusted that one's left margin to push it to the left.
$('#slider').animate({
marginLeft: '-' + ind * 105 + 'px'
});
and back
$('#slider').animate({
marginLeft: 0 + 'px'
});
There is a much easier way altogether of doing this. By using jQuery's scrollTo plugin, this can be done in a mere few lines of code, without using indices, calculations, or anything of that nature.
Live Demo http://jsfiddle.net/Jaybles/WEzny/

Categories