AChillingSight AChillingSight - 9 months ago 40
jQuery Question

How to click to dropdown on mobile and hover on desktop

My menu system right now will display the sub-menu items on click when on mobile and on desktop (as well as hover). I'm trying to have the on click only when on mobile.

I've tried window.resize(), addEventListener and window.width() with no luck. The closest I've got is this

jQuery(document).ready(function($) {
$(window).resize(function() {
if($(window).width() < '720') {
$('.dropdown').click(function(e) {
var childMenu = e.currentTarget.children[1];
if($(childMenu).hasClass('visible')) {
$(childMenu).removeClass('visible');
}else{
$(childMenu).addClass('visible');
}
});
}
});
});


If I load my page in a non-mobile width it works as expected (shows hover, but not on click) then adjust down to mobile size and works there too (shows on click). When I expand it back out it stops working (shows on hover and on click) then shrink it down doesn't work (no show on click) then back and forth as I adjust the screen.

I've looked at numerous solutions here on stack and other websites. For testing I'm using a tablet that when vertical loads the mobile version of the site but when horizontal loads the desktop version. This way I can cover both basis while also testing someone rotating a device.

EDIT: Based off more testing and console.log my window width is changing from 690 to 128.75 when I make the screen larger. I haven't the foggiest why. The script was basing the $(this).width() off of the childMenu var. Updated original code. Still doesn't work though

Answer Source

The first thing I'm noticing is that you don't have an initial run of your script which would cause the two to switch if the initial window was < 720. Also, you're not unbinding the click event.

This should fix that:

       function windowSizeCheck() {
            $('.dropdown').off('click.mobile'); // Prevent duplicate bindings
            if($(window).width() < '720') {
                $('.dropdown').on('click.mobile', function(e) {
                    var childMenu = e.currentTarget.children[1];
                    if($(childMenu).hasClass('visible')) {
                        $(childMenu).removeClass('visible');
                    }else{
                        $(childMenu).addClass('visible');
                    }
                });
             }
        }
jQuery(document).ready(function($) {
        windowSizeCheck();
        $(window).resize(windowSizeCheck);
});

Note: My answer helps attach and detach handlers based on window size Ovais's is more efficient to leave it attached and only do the action on certain window sizes. Both approaches should work.