jQuery toggleClass doesn't fire work resizing browser? - javascript

I have an issue with some code. Basically on click of a div the class 'active-sort' should be added/removed (This class changes the position of .sort-by from the top). On page load it works great but for some reason the toggleClass doesn't always work when the browser is resized (sometimes it does, sometimes it doesn't).
I'm not great with this, so was hoping a new set of eyes might be able to instantly see what I'm doing wrong. Any help would be appreciated.
function toggleSortBy() {
var toggle = $('.sort-banner-row'),
sortBy = $('.sort-by');
if ($(window).width() > 1024) {
toggle.click(function(){
sortBy.toggleClass('active-sort');
});
} else {
// other code here for smaller devices
}
};
$(window).on('load resize', function() {
toggleSortBy();
});

it's possible you may not need the resize event since you're checking the window size already in the click handler
var toggle = $('.sort-banner-row'),
sortBy = $('.sort-by');
toggle.click(function(){
if ($(window).width() > 1024) {
sortBy.toggleClass('active-sort');
} else {
// other code here for smaller devices
}
});
but if you do you should debounce the resize event
//css-tricks.com/snippets/jquery/done-resizing-event
then you could do something like:
var toggle = $('.sort-banner-row'),
sortBy = $('.sort-by'),
isMobile = false;
toggle.click(function(){
if (isMobile) {
sortBy.toggleClass('active-sort');
} else {
// other code here for smaller devices
}
});
$(window).on('load resize', function() {
// don't forget to debounce you'll see why later on in your development.
isMobile = ($(window).width() > 1024) ? false : true;
});

Related

jQuery Scroll up/down animations blocking

I have a problem regarding two animations, one scrolling down and one scrolling up (when the user has scrolled back up completely).
The animations block each other - with the following source code:
jQuery(document).ready(function($) {
$(window).on("load",function() {
$(window).scroll(function(){
if($(window).offset().top == 0){
$("selector").animate({}, 500);
$("selector").animate({}, 500);
} else {
$("selector").animate({}, 500);
$("selector").animate({}, 500);
}
});
}).scroll();
});
So it happens that after the true statement block of the if directly the else part is executed again and therefore the animation is partly not executed at all or both are executed one after the other. Does anyone have an idea that the animations are executed reliably:
else animation once as soon as scrolling down was done
if-Animation as soon as scrolling up completely again
Thanks in advance!
Makes no sense to cauculate $(window).offset().top since... it does what it says. 0.
Perhaps, on "scroll" Event you want to get the $(window).scrollTop()
jQuery($ => {
const $win = $(window);
const $items = $(".item");
$win.on("scroll", () => {
$items.toggleClass("active", $win.scrollTop() == 0);
});
$win.on("load", () => {
$win.trigger("scroll");
});
});
.active {
/* your styles here */
}

GSAP / TweenMax disable desktop animation on mobile and vise versa and also reset on resize

I'm using GSAP / Tweenmax for some animations and I'm very close to where I want the animations to be. I have two different timelines - one for mobile, one for desktop. How can I make sure they each play regarding the window width and also if screen is resized clear to the final state of each animation. I tried using some window width resize calls but now the animations play everytime the browser width is moved at all and I see why with how I'm calling the functions, what is the best way to do this? thanks! :)
js:
$(function () {
function animations() {
if ($(window).width() > 768) {
heroAnimation.play(0);
} else {
heroAnimation.pause(0);
}
}
function animationsMobile() {
if ($(window).width() <= 767) {
heroAnimationMobile.play(0);
} else {
heroAnimationMobile.pause(0);
}
}
$(window).resize(animations);
animations();
$(window).resize(animationsMobile);
animationsMobile();
});
You should keep track of the state and only restart the animation if the state changes. Also only use one function, no need for two:
var state = "";
function animations() {
var newState = state;
if (innerWidth > 768) {
newState = "big";
} else {
newState = "small";
}
if(newState !== state) {
if(newState === "big") {
heroAnimation.play(0);
heroAnimationMobile.pause(0);
} else {
heroAnimation.pause(0);
heroAnimationMobile.play(0);
}
state = newState;
}
}
document.addEventListener("resize", animations);
animations();
By the way, you should totally use GSAP 3! It has a smaller file size, sleeker API, and a bunch of new features!
Also, you're more likely to get an even faster response and additional insight over on the GreenSock forums.

$(window).width() if statement running when it shouldn't

Hey guys I am having an issue with $(window).width if statements in jQuery. For some reason my function is running even when the window width is smaller than 991 pixels however my if statement states that it should run if the window width is greater than 991.
function ctaFixTop() {
var mn = $("#new-car-offer-cta");
var offerHead = $('#new-car-offer-head');
mns = "new-car-offer-cta-active";
var hdr = 0;
var ctaHeight = $("#new-car-offer-cta").height();
$('.header-wrapper, #top-bar, #new-car-back, #new-car-offer-head').each(function() {
hdr += $(this).outerHeight();
});
if ($(window).width() > 991) {
$(window).scroll(function() {
if ($(this).scrollTop() > hdr) {
offerHead.css('margin-bottom', ctaHeight);
mn.addClass(mns);
} else {
offerHead.css('margin-bottom', 0);
mn.removeClass(mns);
}
});
}
}
$(window).resize(ctaFixTop);
ctaFixTop();
As you can see the ctaFixTop function is being called twice, once on initial load and whenever the window is resized. When I initially load the page with a window width below 991px the function works how it should however if I then increase the windows size past 911px and size it back down under 911px the $(window).scroll function will be called even when it's wrapped in the if statement that states that it should only run if the window width is greater than 991.
Any idea why this might be happening as I have tried trouble shooting this and simply can't understand why the function is being called even with the if statement around it.
Thanks
That is because the scroll event is already attached to the window and you are not removing it. What you need to do is put the
if ($(window).width() > 991) {
inside the .scroll() method like this.
$(window).scroll(function() {
if ($(window).width() > 991) {
if ($(this).scrollTop() > hdr) {
offerHead.css('margin-bottom', ctaHeight);
mn.addClass(mns);
} else {
offerHead.css('margin-bottom', 0);
mn.removeClass(mns);
}
}});

function triggers on window width but will not turn off if bigger than set width

Here is what I have now it will work but if window width is under 1024 it will still trigger even though it is only set to trigger if over 1024
$(function () {
$('#hamburger').click(function () {
$('div.burger_nav').slideToggle();
});
$(window).resize(function () {
if ($(window).width() < 1024) {
$('.nav_shown').hide();
$('div.footerdiv_2').hide();
$('div.hidden_nav').hide();
$('div.burger_btn').show();
$('#ft').removeClass('footerdiv_3').addClass('footer_img_clear');
} //end of if
else {
$(".nav_shown").show();
$('.footerdiv_2').show();
$('div.burger_btn').hide();
$('#ft').removeClass('footer_img_clear').addClass('footerdiv_3');
$(document).scroll(function () {
var headerShow = $(this).scrollTop();
if (headerShow > 200) {
$('div.hidden_nav').fadeIn();
$(".nav_shown").hide();
} else {
$('div.hidden_nav').fadeOut();
$(".nav_shown").show();
}
});
} //end of else
});
});
It looks like you want to modify the document when the window reaches a certain breakpoint, in this case 1024 pixels. This is known as responsive web design.
Instead of updating the screen every time on resize, it's useful to set a flag for triggering a breakpoint.
$(function() {
$('#hamburger').click(function(){
$('div.burger_nav').slideToggle();
});
var currentlySmall = false;
function update() {
if ($(window).width() < 1024 && !currentlySmall) {
currentlySmall = true;
console.log('Less than 1024');
$('.nav_shown').hide();
$('div.footerdiv_2').hide();
$('div.hidden_nav').hide();
$('div.burger_btn').show();
$('#ft').removeClass('footerdiv_3').addClass('footer_img_clear');
}
else if ($(window).width() >= 1024 && currentlySmall) {
currentlySmall = false;
console.log('More than 1024');
$(".nav_shown").show();
$('.footerdiv_2').show();
$('div.burger_btn').hide();
$('#ft').removeClass('footer_img_clear').addClass('footerdiv_3');
}
}
//Calling this in the else part above will bind a new scroll event each time
//Instead, if this should only happen when the screen is large, use the
//flag you created
$(document).scroll(function () {
if (!currentlySmall) {
var headerShow = $(this).scrollTop();
if (headerShow > 200) {
$('div.hidden_nav').fadeIn();
$(".nav_shown").hide();
} else {
$('div.hidden_nav').fadeOut();
$(".nav_shown").show();
}
}
});
$(window).resize(update);
update(); //Force initial calculation since resize won't be called when page loads
});
Now the changes you make in the above update() function will only occur when the screen sizes changes past that 1024 breakpoint instead of every time the screen is resized.
Fiddle: http://jsfiddle.net/25nfqxzk/1/
Edit
Expanding off blgt's comment, I don't believe you need to bind the scroll event in the if-else. It can be assigned outside and also use the same trigger flags.

Javascript/Jquery rotating image that re-sizes when window is resized

i can not get this to work, Please help! . it's a mess. What i am trying to do is, make this image blur out and blur a new one in ever few seconds, and if the window size is greater than a defined size, it will use a larger image. Also it needs to check if the window has been re-sized so i can change the image on the go. so i will need something like this:
$(window).resize(function(){
change size
});
this is the main bit of code that i'm having troubles with:
$(document).ready(function() {
var index = 1;
function rotateImage()
{
$('.dp1').fadeOut('slow', function()
{
if($(window).width() > 1312 ) {
$('.dp1').css({'background-image' : 'url(../img/display_banner' + index + '.jpg)'});
}
else {
$('.dp1').css({'background-image' : 'url(../img/display_banner' + index + '_big.jpg)'});
}
$(this).fadeIn('slow', function()
{
if (index == images.length-1)
{
index = 0;
}
else
{
index++;
}
});
});
}
$(document).ready(function()
{
setInterval (rotateImage, 4000);
});
});
First, you only need one .ready() method. :)
To address your question, you can take advantage of .resize() to calculate the window width. Just start with a variable that contains the width, and then recalculate on resize. For example:
$(document).ready(function () {
var index = 1,
width = $(window).width(); // SET THE WIDTH ON DOCUMENT READY
function rotateImage () {
//...
if(width > 1312){ // USE THE "width" variable here in this comparison
//...
}
//SET THE "width" variable on window resize
$(window).resize(function(){
width = $(this).width();
//... RESIZE OR CHANGE OUT IMAGES HERE...
});
});

Categories