Reputation:
What I am trying to achieve is:
A button is added either before or after a menu item, depending on browser size. This works fine on load.
On resize, check for buttons in the 'wrong' place, remove them and add them in the right place. This is not working.
var masthead = $('#masthead');
var dropdownToggle = $('<button />', {'class': 'dropdown-toggle','aria-expanded': false})
var width = $(window).innerWidth();
function addDropdowns() {
if (width > 991) {
$('.menu-item-has-children > a').after(dropdownToggle); // On desktop, add the dropdown after the link
} else {
$(dropdownToggle).insertBefore('.menu-item-has-children > a'); // On mobile, add the dropdown before the link
}
}
addDropdowns();
var dropdownDesktop = masthead.find('.menu-item-has-children > a + button');
var dropdownMobile = masthead.find('.menu-item-has-children > button + a');
var dropdownToggles = masthead.find('button.dropdown-toggle');
var resizeTimer;
$(window).on('resize', function(e) {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(function() {
if (width > 991) { // if desktop ...
if (dropdownMobile.length != 0) { // do mobile dropdowns exist
dropdownToggles.remove(); // if they do, remove them
} else {
if (dropdownDesktop.length != 0) { // do desktop dropdowns exist
return; // if they do, do nothing
} else {
addDropdowns(); // if they do not, add them
}
}
} else { // if mobile ...
if (dropdownDesktop.length != 0) { // do desktop dropdowns exist
dropdownToggles.remove(); // if they do, remove them
} else {
if (dropdownMobile.length != 0) { // do mobile dropdowns exist
return; // if they do, do nothing
} else {
addDropdowns(); // if they do not, add them
}
}
}
}, 250);
});
Outside of this function, (dropdownMobile.length != 0)
and (dropdownDesktop.length != 0)
evaluate correctly and (dropdownToggles.remove();
works too. I am very new to JQuery and Javascript, and have been searching for an answer all weekend. Any pointers gratefully received.
Upvotes: 0
Views: 565
Reputation: 1310
Your problem is width is defined on pageload and not on resize.
var width = $(window).innerWidth();
Define width in resize function:
$(window).on('resize', function(e) {
var resizeWidth = window.innerWidth;
if(resizeWidth < 991) {
// Do something
}
}
What I would also suggest use Throttling or Debounce on 'resize' because it is quite a heavy task for the browser to do this check without Debounce or Throttle.
"Debounce limits the rate at which a function can fire. A quick example: you have a resize listener on the window which does some element dimension calculations and (possibly) repositions a few elements. That isn't a heavy task in itself but being repeatedly fired after numerous resizes will really slow your site down. "
Upvotes: 1