Get last viewed index with Scrollify - javascript

I'm using scrollify to swap out fixed position components, and adding/removing classes to animate the transition. I have everything working as I'd like as you progress forward through the scroll, but when you scroll up to see a previous section, its not removing the previous class, and the previous section now animates in behind it.
I don't think the prev method will be of use, because it doesn't call the previous section your were at, only the previous section assuming you are always moving forward.
Here is my code below, you can move forward just fine, but trying to go backwards presents a problem as the new current section will load behind the previous one, and the previous one will still be visible.
jsfilddle here
var wrapper = $('.wrapper');
var currentPosition = 0;
$(wrapper).each(function(index) {
if (currentPosition != index) {
$(this).css('opacity', 0);
} else if (currentPosition == index) {
$(this).css('opacity', 1);
}
});
$(function() {
$.scrollify({
section: ".wrapper",
scrollSpeed: 700,
setHeights: false,
after: function(index, sections) {
var prevWrapper = $.scrollify.current().prev();
var currentWrapper = $.scrollify.current();
var nextWrapper = $.scrollify.current().next();
$(prevWrapper).removeClass('wrapper-enter').addClass('wrapper-leave');
$(currentWrapper).removeClass('wrapper-leave').addClass('wrapper-enter');
},
});
});

The issue is depending on scrolling up or down your "next" or "prev" may not actually be what you think so you are hiding classes incorrectly.
What you could do as scrollify doesn't have an option to detect scroll direction is to create a super quick variable that will detect if you are scrolling up or down. Then simply update your classes then in the after function.
$.scrollify({
section: ".wrapper",
scrollSpeed: 700,
setHeights: false,
after: function(index, sections) {
var prevWrapper = $.scrollify.current().prev();
var currentWrapper = $.scrollify.current();
var nextWrapper = $.scrollify.current().next();
let elem = null;
// Add wrapper-enter to current element.
$(currentWrapper).removeClass('wrapper-leave').addClass('wrapper-enter');
if(lastIndex < index) {
// Scolled down if lastIndex < index
elem = prevWrapper;
} else {
// Scrolled up if last index > index
elem = nextWrapper;
}
$(elem).removeClass('wrapper-enter').addClass('wrapper-leave');
lastIndex = index;
},
In the above I simply created a variable to track the last index.
Here is a working fiddle: https://jsfiddle.net/k1e6x79f/

Related

remove one class when animating

I try to animate menu-panel. It should slide to the left. But it doesn't work right. And I can't understand why.
There are a few issues with the current code (e.g. you were missing a . on one panel selector and not referencing panel1 after changing the panel class. I also switched to absolute positioning with the arrow inside the panel.
I did a little cleanup to make the changes obvious (you should not repeat jQuery selectors - use temp vars instead):
JSFiddle: http://jsfiddle.net/TrueBlueAussie/2x3uT/8/
$(function () {
$('.slider-arrow').click(function () {
var $this = $(this);
var $panel = $(".panel, .panel1");
var left = -53;
var text = '»';
if ($this.hasClass('hide')) {
text = '«';
left = 0;
}
$panel.animate({
left: left
}, 700, function () {
// Animation complete.
$this.html(text).toggleClass('hide').toggleClass('show');
$panel.toggleClass('panel').toggleClass('panel1');
});
});
});
You can tweak the position numbers to make it match what you wanted.

Making nav bar effects using scroll AND click in jQuery

I want a nav to highlight (or something similar) once a user clicks on it AND when a user scrolls to the corresponding section.
However, on my computer when one clicks on any of the nav events after3, only nav event 3 changes. I'm guessing this is because after one clicks on 4 or 5, the scroll bar is already at the bottom of the page, so 4 and 5 never reach the top. The only div at the top is post 3, so my code highlights nav event 3 and ignores the click.
Is there any way I can fix this? Ive tried if statements (only highlight nav event if it's at the top AND the scrollbar isn't at the bottom or the top isn't the last item).
Here is a more accurate fiddle, using a fix below showing what I am talking about. The fix now highlights on scroll, but if you click option 5, it will not highlight.
$('.option').children('a').click(function() {
$('.option').css('background-color', '#CCCCCC;');
$(this).css('background-color', 'red');
var postId = $($(this).attr('href'));
var postLocation = postId.offset().top;
$(window).scrollTop(postLocation);
});
$(window).scroll(function() {
var scrollBar = $(this).scrollTop();
var allPosts = [];
var post = $('.content').offset();
var lastPost = allPosts.legnth-1
var windowHeight = $(window).height();
var bottomScroll = windowHeight-scrollBar;
$(".content").each(function(){
allPosts.push($(this).attr('id'));
});
i = 0;
for(i in allPosts){
var currentPost = "#"+allPosts[i];
var postPosition = $(currentPost).offset().top;
if (scrollBar >= postPosition){
$('.option').css('background-color', '#CCCCCC');
$('#nav'+allPosts[i]).css('background-color', 'red');
};
};
});
I think you've overdone your scroll() handler, to keep it simple you just needs to check if the scrollbar/scrollTop reaches the '.contents' offset top value but should not be greater than its offset().top plus its height().
$(window).scroll(function () {
var scrollBar = $(this).scrollTop();
$(".content").each(function (index) {
var elTop = $(this).offset().top;
var elHeight = $(this).height();
if (scrollBar >= elTop - 5 && scrollBar < elTop + elHeight) {
/* $(this) '.content' is the active on the vewport,
get its index to target the corresponding navigation '.option',
like this - $('.Nav li').eq(index)
*/
}
});
});
And you actually don't need to set $(window).scrollTop(postLocation); because of the default <a> tag anchoring on click, you can omit that one and it will work fine. However if you are looking to animate you need first to prevent this default behavior:
$('.option').children('a').click(function (e) {
e.preventDefault();
var postId = $($(this).attr('href'));
var postLocation = postId.offset().top;
$('html, body').animate({scrollTop:postLocation},'slow');
});
See the demo.
What you are trying to implement from scratch, although commendable, has already been done by the nice folks at Bootstrap. It is called a Scrollspy and all you need to do to implement it is include Bootstrap js and css (you also need jquery but you already have that) and make some minor changes to your html.
Scrollspy implementation steps.
And here is a demonstration. Notice only one line of js. :D
$('body').scrollspy({ target: '.navbar-example' });

jQuery: Using scroll() and offset() to change background

I am designing a website where the background sits in a div that has a negative z-index with position:fixed. I then have section divs that scroll over it. My goal is to change the background image when each section's top position is passed by the scrollTop function. My jQuery code currently creates an array of each sections top position using:
var secTops = [];
$('section').each(function(i) {
var t = $(this).offset();
secTops.push(t.top);
});
I then thought I would create a variable upon scroll() that was the scrollTop() position like so:
$(window).scroll(function() {
var winTop = $(this).scrollTop();
});
But here is where I am stuck. The best I can come up with (which doesn't work right) is this:
for (i = 0; i < $('section').length; i++) {
var pos = secTops[i];
if (winTop < pos) {
$('#background').css('background', bgFront + (i+1) + bgBack);
} else {
$('#background').css('background', bgFront + (i+2) + bgBack);
};
};
But this isn't right. You can disregard the second half of my .css() function. I've created variables and labeled my images appropriately, so i know that works. Right now, the for loop runs through the entire iteration and is stuck at the full section.length and thus only flips between 2 background images. I need this to constantly check my winTop variable against the top positions of my sections and change the background accordingly. I could do this with a lot of if/then, or maybe even a lengthy switch, but there has to be a cleaner way to do this. Can anyone help me out here?
Here's a JSFiddle that uses colors instead of images but shows the same problems. http://jsfiddle.net/kyleshevlin/5N5WU/1/
this has no chance to work. you need to change it to something like this (this is kinda pseudocode, just to give you a picture:
sections = [];
$(document).ready(function() {
$('section').each(function() {
sections.push($(this))
});
})
$(window).scroll(function() {
var s = $(window).scrolTop();
var currentIndex;
for ( var i = 0; i < sections.length; i++) {
if (( s > sections[i].offset().top) && ( s <= sections[i+1].offset().top)) {
currentIndex = i;
}
}
$('#background').css('background', bgFront + (i+1) + bgBack);
})

Clicking on Same button to Reverse Javascript effect

So I am very very new to JavaScript and unfortunately I don't know the basics too well also.
I was working on a code to make an element hidden after clicking it and again reversing back the effect by clicking the same button but I am unable to do so. Please help me here is the code:
$(function() {
$('#boxclose').click(function(){
$('#md-share-window').animate({'bottom':'-90px'},500,function(){});
});
});
You can use a class to identify the state of the element you are animating.
Here's an example: http://jsfiddle.net/FgDaq/
$('#boxclose').click(function() {
var c = 'on',
el = '#md-share-window',
duration = 500;
if ($(el).hasClass(c)) {
$(el).animate({'bottom': 0}, duration)
.removeClass(c);
} else {
$(el).animate({'bottom': '-90px'}, duration)
.addClass(c);
}
});
You'll need to get the initial position (or hard code it) and keep track of whether you are in the initial or updated position:
$(function() {
var shareWindow = $('#md-share-window');
var initialPosition = shareWindow.css('bottom'); //get initial position
var atInitialPos = true; //whether this is the initial or updated position
$('#boxclose').on('click', function(){
var newPosition = atInitialPos ? '-90px' : initialPosition; //determines new position
shareWindow.animate({'bottom': newPosition}, 500);
atInitialPos = !atInitialPos; //toggle initial position boolean
});
});

jQuery scroll to div on hover and return to first element

I basically have a div with set dimensions and overflow: hidden. That div contains 7 child divs (but only shows one at a time) that I would like to be smoothly scrolled through vertically when their respective links are hovered.
However, the first section (div) doesn't have a link and is the default section when no link is hovered.
Take a look at this jsFiddle to see a basic structure of what I'm talking about: http://jsfiddle.net/YWnzc/
I've attempted to accomplish this with jQuery scrollTo but haven't been able to get it to work.
Any help would be greatly appreciated. Thanks.
Something like this?
http://jsfiddle.net/YWnzc/5/
code:
jQuery("#nav").delegate("a", "mouseenter mouseleave", function (e) {
var i, self = this,
pos;
if (e.type == "mouseleave") {
i = 0;
}
else {
//Find out the index of the a that was hovered
jQuery("#nav a").each(function (index) {
if (self === this) {
i = index + 1; //the scrollTop is just calculated from this by a multiplier, so increment
return false;
}
});
}
//Find out if the index is a valid number, could be left undefined
if (i >= 0) {
//stop the previous animation, otherwise it will be queued
jQuery("#wrapper").stop().animate({
scrollTop: i * 200
}, 500);
//I would retrieve .offsetTop, but it was reporting false values :/
}
e.preventDefault();
});
FYI : That JSFIDDLE you sent me to went to MooTools framework, not jQuery... fyi. (might be why its not working?
Copy and paste this code exactly and it will work in jQuery for animated scrolling.
Try this for smooth scrolling within the DIV, I tested it - it works great. You
$(function() {
function filterPath(string) {
return string
.replace(/^\//,'')
.replace(/(index|default).[a-zA-Z]{3,4}$/,'')
.replace(/\/$/,'');
}
var locationPath = filterPath(location.pathname);
var scrollElem = scrollableElement('#wrapper');
// Any links with hash tags in them (can't do ^= because of fully qualified URL potential)
$('a[href*=#]').each(function() {
// Ensure it's a same-page link
var thisPath = filterPath(this.pathname) || locationPath;
if ( locationPath == thisPath
&& (location.hostname == this.hostname || !this.hostname)
&& this.hash.replace(/#/,'') ) {
// Ensure target exists
var $target = $(this.hash), target = this.hash;
if (target) {
// Find location of target
var targetOffset = $target.offset().top;
$(this).click(function(event) {
// Prevent jump-down
event.preventDefault();
// Animate to target
$(scrollElem).animate({scrollTop: targetOffset}, 400, function() {
// Set hash in URL after animation successful
location.hash = target;
});
});
}
}
});
// Use the first element that is "scrollable" (cross-browser fix?)
function scrollableElement(els) {
for (var i = 0, argLength = arguments.length; i <argLength; i++) {
var el = arguments[i],
$scrollElement = $(el);
if ($scrollElement.scrollTop()> 0) {
return el;
} else {
$scrollElement.scrollTop(1);
var isScrollable = $scrollElement.scrollTop()> 0;
$scrollElement.scrollTop(0);
if (isScrollable) {
return el;
}
}
}
return [];
}
});
FYI : Credit for this code does not go to me as an individual developer, although I did slightly tweak the code. The owner and creator of this code is Chris Coyier and you can find more about this scrolling code here:
http://css-tricks.com/snippets/jquery/smooth-scrolling/
Here's a working example: http://jsfiddle.net/YWnzc/7/
And the code (pretty similar to rizzle's, with a couple changes that I'll explain):
$('a').hover(function(){
var selector = $(this).data('section');
var scrollAmount = $(selector).offset().top + $('#wrapper')[0].scrollTop - 129;
$('#wrapper').animate({scrollTop: scrollAmount}, 250);
},function(){
$('#wrapper').animate({scrollTop: 0}, 250);
});
First, var selector = $(this).data('section'); because in jsFiddle, the href attribute was returning the full path of the page + the hash. So I changed it to an html5 data attribute (data-section).
The next line is similar to rizzle's, except that we grab the offset of the section and add it to the current scrollTop value of the #wrapper. As he pointed out, there are some weird offset issues going on still, and I found that subtracting 129 did the trick. While this 129 number might seem like something that is likely to break, I did test out changing the sizes of the sections, making them not equal, etc, and it continued to work. I'm using Chrome, and perhaps a non-webkit browser would need a different constant to subtract. But it does seem like that 129 number is at least some kind of constant.
The rest should be pretty self-explanatory.
One thing to note: as you move your cursor over the <a> tags, the content of the #wrapper div will seem to jump around, but that's just because the mouseleave part of the hover event briefly gets triggered as the cursor moves. I'm sure you can solve that one though :)
$("#nav a").hover(function () {
var sectionName = $(this).attr("href");
var sectionPos = $(sectionName).offset().top;
var wrapperPos = $("#wrapper").offset().top;
var wrapperScroll = $("#wrapper").scrollTop();
var scrollPos = sectionPos - wrapperPos + wrapperScroll;
$("#wrapper").stop().animate({scrollTop:scrollPos}, 600);
}, function () { $("#wrapper").stop().animate({scrollTop:0}, 600); });

Categories

Resources