As I work on making my website responsive, I have encountered an issue with the jQuery script. When rapidly changing the window size, it seems to ignore the conditions set for elements to be displayed or hidden.
The CSS is straightforward:
body:after{display:none; content:"default";}
@media only all and (max-width: 800px){
body:after{content:"tablet";}
}
And the jQuery code is as follows:
jQuery(document).ready(function($) {
var currentSize = "default";
var lazyLayout = _.debounce(function(e) {
}, 300, true);
$(window).resize(lazyLayout,function() {
var size = window.getComputedStyle(document.body, ':after').getPropertyValue('content');
size = size.replace(/"/g, "");
size = size.replace(/'/g, "");
if (size != currentSize) {
if (size == 'tablet') {
var count = $('#mobileNav').length;
if (count < 1) {
var data = {
dataType: "HTML",
action: 'nav_media_query',
nonce: myAjax.nonce
};
$.post( myAjax.url, data, function( data ) {
$('#content-wrapper').removeClass('col-4-5');
$('#trending-Container').addClass('mobileNavStyle');
$('#trending-Container').append(data);
});
currentSize = 'tablet';
}
}
if(size == 'default') {
$('#mobileNav').remove();
currentSize = 'default';
}
}
}).resize();
});//end function
This script checks for a media query by examining the content attribute, then triggers an ajax request to load WordPress PHP into an element.
While this setup works well with gradual window resizing, it tends to break when resizing quickly and repeatedly.
Is there a jQuery method that can prevent this issue from occurring?
Edit: I have updated my code to include _.js debounce method in order to reduce the number of ajax requests. However, the problem of elements not being removed after the conditions are no longer met remains unresolved.