The Great Hambino The Great Hambino - 1 month ago 4
jQuery Question

Firing different functionality on resize

I've tried googling this but I'm not entirely sure what keywords I should be using, so I'm coming up empty. In any case, I feel like I'm missing something relatively simple in my functions and the way they're firing.

My desired functionality is this: I have a little arrow next to my nav, with the structure ".menu-item-has-children a i". On mobile (below 880px), I want to click that element and have it toggle the below. On desktop, I don't. That works just fine until I'm switching between those two viewport sizes (below 880 and above 880). Then the desired functionality won't fire until I reload the page. My jQuery looks like this:

jQuery(document.ready(function($) {
function mobileNav() {
var w = $(window).width();

if (w < 879) {
$('.menu-item-has-children a i').click(function(e) {
e.preventDefault();
$(this).parents('menu-item-has-children').children('ul').toggle();
$(this).toggleClass('turned');
});
}
}

mobileNav();

jQuery(window).resize(function($) {
mobileNav();
});
});

Answer

Im not exactly sure but I think the reason it wasn't working is because there is no . in front of menu-item-has-children in the line with $(this).parents('menu-item-has-children').children('ul').toggle();

fwiw, you can use the delegate syntax of the click handler which eliminates the need for domReady and eliminate the resize function, because we don't actually run any behavior when the screen is resized. We only care what happens when .menu-item-has-children a i nodes are clicked. So we can check the screen size on each click.

   jQuery(document).on('click', '.menu-item-has-children a i', function(e) {
       var $ = jQuery;
       var $this = $(this);
       e.preventDefault();
       if (879 < $(window).width()) {
           $this.parents('.menu-item-has-children').children('ul').toggle();
           $this.toggleClass('turned');
       }
   });
Comments