Skip to content

Instantly share code, notes, and snippets.

@jaclyntan
Created June 30, 2020 07:43
Show Gist options
  • Save jaclyntan/40c3f0b5fa8bc0771084a6a6e727c5ec to your computer and use it in GitHub Desktop.
Save jaclyntan/40c3f0b5fa8bc0771084a6a6e727c5ec to your computer and use it in GitHub Desktop.
Parallax any element on the page using jquery and data attributes
/*!
♡♡♡♡♡♡♡♡♡♡♡
♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥
Parallax functionality
♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥
♡♡♡♡♡♡♡♡♡♡♡
*/
$('.parallax').on('mouseover', function () {
$(this).css('z-index', '99');
});
$('.parallax').on('mouseout', function () {
$(this).css('z-index', 'initial');
});
var winScrollTop = 0;
$.fn.is_on_screen = function () {
var win = $(window);
var viewport = {
top: win.scrollTop(),
left: win.scrollLeft()
};
//viewport.right = viewport.left + win.width();
viewport.bottom = viewport.top + win.height();
var bounds = this.offset();
//bounds.right = bounds.left + this.outerWidth();
bounds.bottom = bounds.top + this.outerHeight();
return (!(viewport.bottom < bounds.top || viewport.top > bounds.bottom));
};
function parallax() {
var scrolled = $(window).scrollTop();
$('.parallax').each(function () {
if ($(this).is_on_screen()) {
var firstTop = $(this).offset().top;
// var $span = $(this).find(".img");
var moveTop = (firstTop - winScrollTop) * $(this).attr('data-speed') //speed;
$(this).css("transform", "translateY(" + -Math.min(0, moveTop) + "px)");
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment