Reputation: 181
I'm pretty new to jQuery and hope to find some help from you guys. I managed to create some scrolling function that works with dynamic built content.
I have a couple of DIVs to which I want to "scrollTo". These Divs are always as big as the viewport. Everything works fine until I resize the window. on window resize the resizeDiv and the setScrollingPoints are fired again. The now is that the animation goes to the old coordinates and slowly scrolls then to the right position.
I found out, that the resize functions is called multiple times and therefore the setScrollingPoints function is fire multiple times as well. What I don't understand is why the old positions are not overwritten. Maybe you can help me out...
Thx a lot! Dan
My code looks like that:
function resizeDiv(target) {
// resizing Divs
var viewportHeight = $(window).height();
var viewportWidth = $(window).width();
$(target).height(viewportHeight).width(viewportWidth);
} // end resize Divs
function setScrollingPoints() {
var wallpapers = $('.wallpaper');
var buttons = $('.button');
var scrollPositions = new Array();
// Cache Wallpaper positions
wallpapers.each(function(i) {
scrollPositions[i] = Math.round($(this).offset().top);
$(this).addClass('wallpaper'+ i);
});
// setting next Buttons
buttons.each(function(i) {
$(this).attr('id','button'+i);
if(i == wallpapers.length - 1) {
$(this).remove();
}
});
$('.nextButton').click(function() {
// get button id
var elementID = $(this).attr('id');
// remove alpha characters from id and convert it to a numeric var
elementID = parseInt(elementID.replace(/\D/g,''));
var next = elementID + 1;
var previous = elementID -1;
var nextWallpaper = '.wallpaper' + next;
var previousWallpaper = '.wallpaper' + previous;
if(!(next == wallpapers.length)) {
$('html, body').scrollTo(scrollPositions[elementID+1]);
});
});
$(window).resize(function() {
resizeDiv('.wallpaper');
setScrollingPoints();
});
$(document).ready(function() {
// resize all wallpaper elements to viewport size
resizeDiv('.wallpaper');
// set scrollingPositions
setScrollingPoints();
});
Upvotes: 0
Views: 482
Reputation: 1184
In setScrollingPoints, change:
var scrollPositions = new Array();
to
scrollPositions = new Array();
If you take the var keyword from infront of your referenced to scrollPositions, you will be talking about the global scope scrollPositions, which would be accessible to any of your functions.
Different Issue:
You have
$(this).addClass('wallpaper'+ i);
in setScrollingPoints. You're not removing previous classes.
Final Issue
Just looked at your JSfiddle (thank you for making it for me).
Your problem isn't your array. Inside of setScrollingPoints()
you're setting the click listener:
$('.nextButton').click(function() {
This doesn't overwrite the previous listener, it just adds another one. You need to add this:
$('.nextButton').off("click");
above $('.nextButton').click(function() {
you were simply triggering all of the old listeners on each button.
Upvotes: 1