parallax

Effet parallax avec jQuery

Un gros bout de code en jQuery pour faire un effet parallax sur un élément donné. Je le colle là sans trop d'explications, j'ai beaucoup trop de choses à faire pour tout commenter.


/*
* Adds a parallax effect to a background image
* (position:fixed;no-repeat;background-size:42%;)
*
* element : the element with a background image
* percent : percent of the background-size (0.42)
* height : height of the background image
* width : width of the background image
* factor : factor of speed (the lower the faster)
* reference : the element bottom-placed to get the total
*             height of the page
*
* author : Guillaume Litaudon  <guillaume.litaudon@gmail.com>
*/

function parallax(element,percent,height,width,factor,reference){
	var winWidth = $(window).width();
	var winHeight = $(window).height();

	var sizePercent = percent == 1 ? height : ((winWidth*percent)/width)*height;

	var maxScroll = -(sizePercent - winHeight);
	var speed = factor*($(reference).offset().top / winHeight);
	var yPos = -($(window).scrollTop() / speed);
	yPos = yPos >= 0 ? 0 : yPos;
	yPos = yPos >= maxScroll ? yPos : maxScroll;
	var coords = '0 '+ yPos + 'px';

	$(element).css({ backgroundPosition: coords });
}


function goGoParallaxEffect(){
	/* La taille dépend de si l'on est en-dessous
	* de pictureWidth ou non
	*/
	var pictureHeight = 1080;
	var pictureWidth = 388;

	if($(window).width() > pictureWidth)
		parallax('#page',0.42,pictureWidth,pictureHeight,5,footer);
	else
		parallax('#page',1,pictureWidth,pictureHeight,5,footer);
}

$(window).scroll(function() {
	goGoParallaxEffect();
});

$(window).resize(function() {
	goGoParallaxEffect();
});	
Haut de page