How to stop JS running on certain breakpoints

Hi there,

I currently use this JS code to make my menu add a class when scrolling down

jQuery(document).ready(function($) {
$(window).scroll(function() {
	var scrollPos = $(window).scrollTop(),
	navbar = $('.x-navbar');

	if (jQuery('body').hasClass('home')) {
		if (scrollPos > 100) {
			navbar.addClass('alt-color');
		} else {
			navbar.removeClass('alt-color');
		}
	} else {
		if (scrollPos > 1) {
			navbar.addClass('alt-color');
		} else {
			navbar.removeClass('alt-color');
		}
	}
});
});

jQuery(document).ready(function($) {
$(window).scroll(function() {
	var scrollPos = $(window).scrollTop(),
	navbar = $('.x-navbar');

	if (jQuery('body').hasClass('home')) {
		if (scrollPos > 100) {
 $('.x-navbar-fixed-top .x-brand img').attr('src','//staging.dwanedigital.co.uk/wp-content/uploads/2019/09/Dwane-Digital-Logo-Black.png');     
		} else {
			$('.x-navbar .x-brand img').attr('src','//staging.dwanedigital.co.uk/wp-content/uploads/2019/09/Dwane-Digital-Logo-White.png');
		}
	} else {
		if (scrollPos > 1) {
			 $('.x-navbar-fixed-top .x-brand img').attr('src','///staging.dwanedigital.co.uk/wp-content/uploads/2019/09/Dwane-Digital-Logo-Black.png');
		} else {
			$('.x-navbar .x-brand img').attr('src','//staging.dwanedigital.co.uk/wp-content/uploads/2019/09/Dwane-Digital-Logo-White.png');
		}
	}
});
});

Which works fine. However i’m looking to add a responsive menu on my site similar to the below

However my CSS code using a media query doesn’t work and I believe it’s due to the JS. How can I get it so my JS only runs on screen sizes above 979px (so when the menu doesn’t condense down).

I worked out why the background wasn’t working and it was an issue with my CSS. I was using rgba background color but left a space between rgba and the first opening bracket.

However the original question still stands as it still adds the alt-color class on mobile but I don’t want it to.

Hi Ryan,

To avoid the jquery function to work on a certain breakpoints, we can wrap the code inside an if statement:

if($(window).width() > 980) {
  // the entrie function  goes here
}

Adjust 980 breakpoint as needed.
For complete reference see this link.

Hope this helps.

Brilliant, thanks for that Lely!

You’re welcome, Ryan.

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.