Reputation: 411
I created a JQuery script, which fade in a sidebar, when scrolling down for 500px. This is working without any errors. However, I tried to wrap it in another function, which checks the media size. The fade in should only work, if the media size is greater than 1024. It does not work and I don't get any error in the console. Can you pls help me?
jQuery(function($) {
function checkPosition() {
if (window.matchMedia('(min-width: 767px)').matches) {
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 500) {
$("body").addClass("right_side_menu_opened");
$(".side_menu").addClass("nav-fade");
}
else {
$("body").removeClass("right_side_menu_opened");
$(".side_menu").removeClass("nav-fade");
}
});
} else {
}
}
});
Upvotes: 1
Views: 149
Reputation: 2207
You have wrapped the whole JS inside a function which never gets called.
You should
function checkPosition()
)checkPosition()
)Removing the declaration:
jQuery(function($) {
if (window.matchMedia('(min-width: 767px)').matches) {
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 500) {
$("body").addClass("right_side_menu_opened");
$(".side_menu").addClass("nav-fade");
}
else {
$("body").removeClass("right_side_menu_opened");
$(".side_menu").removeClass("nav-fade");
}
});
} else {
}
});
Calling the function:
jQuery(function($) {
function checkPosition() {
if (window.matchMedia('(min-width: 767px)').matches) {
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 500) {
$("body").addClass("right_side_menu_opened");
$(".side_menu").addClass("nav-fade");
}
else {
$("body").removeClass("right_side_menu_opened");
$(".side_menu").removeClass("nav-fade");
}
});
} else {
}
}
checkPosition();
});
Note: if you want to check viewport size, you could use $(window).width();
to get the width of viewport.
Upvotes: 1