I'm trying to build a Parallax Scrolling type website (hiding and unhiding multiple "slides" on a single html page)
I have the basic jQuery code set-up which works as it is:
var main = function() {
$('.to-the-articles').click(function() {
var currentSlide = $('.active-slide');
var nextSlide = $('.active-slide').next();
currentSlide.fadeOut(1200).removeClass('active-slide');
nextSlide.fadeIn(1200).addClass('active-slide');
});
$('.nav-level1').click(function() {
var currentSlide = $('.active-slide');
var nextSlide = $('.active-slide').next();
currentSlide.fadeOut(0).removeClass('active-slide');
nextSlide.fadeIn(1200).addClass('active-slide');
});
$('.nav-level2').click(function() {
$('.active-slide').fadeOut(0).removeClass('active-slide');
$('.level2').fadeIn(1200).addClass('active-slide');
});
$('.nav-level3').click(function() {
$('.active-slide').fadeOut(0).removeClass('active-slide');
$('.level3').fadeIn(1200).addClass('active-slide');
});
$('.nav-level4').click(function() {
$('.active-slide').fadeOut(0).removeClass('active-slide');
$('.level4').fadeIn(1200).addClass('active-slide');
});
$('.back-home').click(function() {
$('.active-slide').fadeOut(0).removeClass('active-slide');
$('.home').fadeIn(1200).addClass('active-slide');
});
};
$(document).ready(main);
As you can see I repeat the same action multiple times, just changing the target to make the active slide.
I have had a go at reducing the code:
var fade = function(target) {
var nextSlide = $(target);
$('.active-slide').fadeOut(0).removeClass('active-slide');
nextSlide.fadeIn(1200).addClass('active-slide');
};
var main = function() {
$('.to-the-articles').click(fade('.home'));
$('.nav-level1').click(fade('.level1'));
$('.nav-level2').click(fade('.level2'));
$('.nav-level3').click(fade('.level3'));
$('.nav-level4').click(fade('.level4'));
$('.back-home').click(fade('.home'));
};
$(document).ready(main);
Here I tried to create a function fade which is called when one of the selected classes are clicked, but instead it just runs the functionfade as soon as the document is ready.
Could someone explain why function fade runs on $(document).ready and doesn't wait for the .click()?
Edit:
Here is the current working code, the first one above: http://jsfiddle.net/m924B/1/ (Note: don't know how to load the images, but if you click the smaller missing image it will take you to the landing page.)
Here is the second attempt at the code: http://jsfiddle.net/m924B/2/