Modernizr media query triggering inconsistently - javascript

I'm trying to have my script trigger only when the screen size is above a specific size (800px), not just on load, but on screen resize.
I've put it inside a Modernizr mq script, but it's triggering inconsistently. Sometimes it will trigger my script at a small screen size.. sometimes at large.. sometimes not at all. Which leads me to believe that I've completely screwed it up!
Can anyone point me in the right direction?
$(function() {
$(window).resize(function(){
if (Modernizr.mq('(min-width: 800px)')) {
// script to trigger
$('.dropdown').on('mouseenter mouseleave click tap', function() {
$(this).toggleClass("open");
});
}
}).resize();
});

Could be because you are triggering the resize event from the resize event, which causes an infinite looping of event triggering.
Also, why not just test the screen size directly?
$(function() {
$(window).resize(function(){
// Use this for browser width: if(window.innerWidth >= 800)
if (screen.width >= 800) {
// script to trigger
$('.dropdown').on('mouseenter mouseleave click tap', function() {
$(this).toggleClass("open");
});
}
});
});

Related

Remove scroll function upon window resize/media query

I have a navigation menu set to display:none, which appears upon scroll and disappears once back at the top.
Is there a way to disable the scroll function once I reach a certain breakpoint (ex. max-width: 786px) and display the menu?
Javascript
$(window).on("scroll", function() {
if($(window).scrollTop()) {
$('nav').addClass('show');
}
else {
$('nav').removeClass('show');
}
})
CSS
.show {
display: block
}
You can solve this using either javascript or CSS, however I would personally go with the javascript one.
First up, for a javascript solution, the function you need is:
window.innerWidth
It will return the entire window width not including scroll bars. Read more about it here.
So, as Temani Afif suggested, you would write a test inside your scroll function to check for the desired window width like so:
$(window).on("scroll", function() {
if (window.innerWidth <= 786) return;
// Your other code here
})
For a purely CSS solution, you could override the effect of the 'show' class with a media query:
.show {
display: block
}
#media screen and (max-width: 786px) {
nav {
display: block !important
}
}
More on media queries here
You can activate/deactivate the scroll listener on browser resize. This way your scroll listener wont be called everytime user scrolls when browser width is more than 786px.
var scrollListenerActive = false;
var handleScrollListener = function() {
if( $(window).width() < 786 && !scrollListenerActive ) {
$(window).on("scroll", function() {
if($(window).scrollTop()) {
$('nav').addClass('show');
}
else {
$('nav').removeClass('show');
}
});
scrollListenerActive = true;
} else {
$(window).off("scroll");
scrollListenerActive = false;
}
}
$(document).ready(handleScrollListener); // attach the listener on page load
$(window).resize(handleScrollListener); // attach/remove listener on window resize
That's a good strategy above, however the event you want to listen for is simply 'resize', on the window object (some older browsers can do it on any dom element, but better to be consistent and current with the standard).
So something like:
window.addEventListener('resize',function(){
if(window.innerWidth >= 768){
document.body.style['overflow-x'] = 'hidden';
}
else{
document.body.style['overflow-x'] = 'auto';
}
});
You can trade 'auto' for 'scroll' if you want the scrollbar to always show when less than 768.
Similarly, you can switch out 'overflow' instead of 'overflow-x' if you want to affect both scrollbars.
Keep in mind that the event tends to fire for every width and height change as the window is resized, in case you have other logic that might have an issue with firing many times (thousands or more) as it is resized.
This also works on maximize/restore, as they trigger the resize event as well.
Here's MDN's doc on the resize event if needed:
https://developer.mozilla.org/en-US/docs/Web/Events/resize
This is vanilla javascript, so it should work whether you're using a lib like jquery or not.

Run jQuery script on load and on resize for responsive

I have a script for my dropdown menu. I would like the responsive (1024px) it turns off. And when I enlarge my window, he reactivates.
I managed to do more or less something that worked:
$(window).resize(function () {
if ($(this).width() > 1024 ){
w.accessibleMenuConfig.init();
}
});
Unfortunately, with this solution, when I load my page in desktop mode (> 1024px), I have to resize my window (one pixel is enough) to activate the script.
And if I shrink my window (I switch from desktop mode to mobile mode), the script is activated on mobile.
I tried this, but it does not work at all :
$(window).on('load resize', function (e) {
if ($(window).width() > 1024 ){
w.accessibleMenuConfig.init();
}
})
Thank you for your help !
You need to handle both page load and resize events for this to work.
I would start with creating a function that does that logic:
function changeAccessibility() {
if ($(window).width() > 1024 ){
w.accessibleMenuConfig.init();
}
}
Then, call the function on each of these events (window resize and window load - the latter happens only once).
$(document).ready(function() {
changeAccessibility();
});
$(window).resize(function () {
changeAccessibility();
});
The resize event is sent to the window element when the size of the browser window changes.
$( window ).resize(function() {
enter code here
});
Check this: https://api.jquery.com/resize/

Resizing window always trigger a click event

I have a bootstrap sidebar that can be toggled into a narrow icon bar, and now I am required to show the sidebar when screen height is greater than 768, and to a narrow side bar when height is lower than 768. But my script appears to be triggering a click event when lower than 768, therefore if I resize the screen multiple times, and when height reaches lower than 768, it continuously toggles the sidebar multiple times. If the height reaches greater than 768, the toggling stops.
My code is:
$("#menu-toggle").click(function(e) {
e.preventDefault();
$("#wrapper").toggleClass("toggled");
$("span", this).toggleClass("fa fa-lock fa fa-unlock");
});
$("#menu-toggle-2").click(function(e) {
e.preventDefault();
$("#wrapper").toggleClass("toggled-2");
$("span", this).toggleClass("fa fa-lock fa fa-unlock");
});
$(document).ready(function() {
var $window = $(window);
// Function to handle changes to style classes based on window width
function checkWidth() {
if ($window.height() <= 768) {
$("#wrapper").toggleClass("toggled-2");
}
else if ($window.height() > 768) {
$("#wrapper").toggleClass("toggled");
}
}
// Execute on load
checkWidth();
// Bind event listener
$(window).resize(checkWidth);
});
Any help is appreciated and thanks in advance.
Are you sure the click event is triggering? (Try making a log inside the click function(s) to confirm using console.log)
Based on the code you posted it looks like resize may be firing multiple times as you resize the window.
Try using the following:
$(window).resize($.throttle(checkWidth, 300));
Throttle returns a new function that executes no more than once every 300ms (or whatever delay you decide to set)
Note: This uses jQuery debounce/throttle plugin
https://code.google.com/archive/p/jquery-debounce/

jQuery: How to trigger windows resize event when scrollbar appears

When vertical scrollbar appears on the page, windows resize event need to be triggered. Is there any way to capture scrollbar appearance event using javascript?
I'm having problem with the width of the page as it makes div to jump to next line when the vertical scrollbar appears. It seems to work fine when I resize page, so I want to trigger resize event manually when vertical scrollbar appears.
You could use setInterval to monitor for the scrollbar. If the document width exceeds the window width, you can trigger the window.resize event manually.
function checkForScrollbar() {
if ($(window).width() < $(document).width()) {
$(window).trigger('resize');
}
}
$(document).ready(function() {
setInterval(function() { checkForScrollbar(); }, 500);
$(window).on('resize', function() {
//Resize triggered.
//Do Your Stuff
});
});
See this JS Fiddle: http://jsfiddle.net/USvsW/9/
OrganicPanda has posted a clever solution without the need for a timer. Basically he places an iFrame with 100% somewhere and listens to 'resize' events on it:
Detect when window vertical scrollbar appears
u can use this:this will through alert on resize
$(window).on('load resize', function(){
var w1 = $(window).width();
alert(w1);
})

Getting wrong screen height when trigger orientationchange event

I wrote the code below to check my mobile screen height when I rotate it to Portrait or Landscape.
window.addEventListener("orientationchange", function(event) {
rotateScreen();
}, false);
function rotateScreen() {
alert(window.orientation)
alert($(window).height())
}
When I rotate it to Portrait, I get 0, 294. When I rotate it to Landscape, I get 90, 419. The figure is reversed, I have tried to wrap it in $(document).ready() but it does not work.
$(document).ready(function(){
alert($(window).height())
})
It looks like that when I rotate the mobile to Portrait, I get the height of Landscape, and when I rotate the mobile to Landscape, I get the height of Portrait. Can someone suggest how to fix it?
Thanks
The resize event gets triggered after the orientationchange event. However resize can also get triggered by other things such as showing the virtual keyboard.
So to get round this we can listen first for an orientationchange, once that occurs we can then add a resize listener. Once the orientationchange has completed it will fire our resize event. Once completed we then remove the resize listener to prevent it being fired in error
$(window).on('orientationchange', function() {
var orientationChange = function(evt) {
rotateScreen();
$(window).off('resize', orientationChange);
}
$(window).on('resize', orientationChange);
});
This effectively creates a kind of pseudo post:orientationChange event. (I would probably avoid using timeouts if you can)
Adding setTimeout could solve the problem, please try the code below:
function rotateScreen() {
window.setTimeout(function() {
alert(window.orientation)
alert($(window).height())
}, 500);
}

Categories

Resources