I have a jQuery function which should only be fired when a certain media query is true (both on ready and resize).
I found a cool trick to check if a certain media query is true:
HTML
<div id="isthin"></div>
CSS
#isthin {
display: inline-block;
content: '';
width: 1px;
height: 1px;
overflow: hidden;
}
@media only screen and (max-width: 1047px) {
#isthin {
display: none;
}
}
jQuery
$(document).ready(function(){
if ( $('#isthin').is(":visible") ) {
// function should be fired
} else {
// function should not be fired
}
});
$(window).resize(function(){
if ( $('#isthin').is(":visible") ) {
// function should be fired
} else {
// function should not be fired
}
});
Separate jQuery function
$(function () {
$('nav li ul').hide().removeClass('sub-nav');
$('nav li').hover(function () {
$('ul', this).stop().slideToggle(300);
});
});
That was my logic but somehow the function still runs on resizing when the media query changes.
The probleme is not the media query itself, but the way you are binding your event.
You're binding it on every resize when the query fits. You should really detach all your function and use a flag. Just like that :
var flag = true;
$(window).resize(function(){
flag = $('#isthin').is(":visible");
if(flag){
$('nav li ul').hide().removeClass('sub-nav');
}else{
$('nav li ul').show().addClass('sub-nav');
}
})
$(document).ready(function(){
$(window).trigger('resize');
})
$(function () {
$('nav li').hover(function () {
if(flag){
$('ul', this).stop().slideToggle(300);
}
});
});
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments