I want to stop the parallax effect on mobile or window resize. I'm using jQuery for the parallax effect with the code below. I cannot figure out how to do that.
$(window).scroll(function(e){
parallax();
});
function parallax(){
var scrolled = $(window).scrollTop();
$('.background').css('top',-(scrolled*0.0100)+'rem');
$('.home-heading').css('top',-(scrolled*0.0100)+'rem');
$('.page-banners').css('top',-(scrolled*0.0100)+'rem');
$('.header-text > h1').css('top',-(scrolled*-0.510)+'rem');
};
Any help is appreciated.
I think the most optimised way would be to either completely add or remove the event listener based on the screen width - using a namespace will prevent it interfering with other scripts :
$(function() {
var gate = $(window);
check();
gate.resize(check);
function check() {
gate.off('scroll.parallax');
if (gate.width() > 1024) gate.on('scroll.parallax', parallax);
}
function parallax() {
// scroll code
}
});
Mostly useful this way with an orientation change - going below the required width when the function was already activated.
Probably not very necessary in practice but here's a variation that only attaches or removes the event listener once, based on if it already exists or not. Looks like there's no easy way (anymore) to check with jQuery directly if an event is attached so a good old flag will do the job :
$(function() {
var gate = $(window), attached;
check();
gate.resize(check);
function check() {
if (gate.width() > 1024) {
if (!attached) {
gate.on('scroll.parallax', parallax);
attached = true;
}
}
else if (attached) {
gate.off('scroll.parallax');
attached = false;
}
}
function parallax() {
// scroll code
}
});
<p>
No active snippet present, just here to minimise the post.</br>
Code could be pasted into demo available above.
</p>
Less elegant but just for completeness.
Edit...
Looks like there's no easy way (anymore) to check with jQuery directly if an event is attached
Actually, it is still feasible. May make no more sense than using a flag or is guaranteed to function correctly in all cases but it's kind of fun to figure out and show it's possible.
$(function() {
var gate = $(window);
check();
gate.resize(check);
function check() {
var handlers = $._data(gate[0]).events;
if (handlers && handlers.scroll)
var attached = handlers.scroll[0].namespace == 'parallax';
if (gate.width() > 1024) {
if (!attached) gate.on('scroll.parallax', parallax);
}
else if (attached) gate.off('scroll.parallax');
}
function parallax() {
// scroll code
}
});
<p>
No active snippet present, just here to minimise the post.</br>
Code could be pasted into demo available above.
</p>