1

I have this mobile menu that I'm currently building at the moment and I'm facing an issue with on('click') events. Whenever I try resizing the browser the event fires multiple times. At first load the script and event works fine, but when I start resizing the browser the event fires multiple times.

Below is a sample of the code I'm working on. Is there a way it fires only when once after resizing. I tried a temporary solution but it does not seem to take effect.

(function($){
    'use strict';

    var mobileMenu = {

        init : function() {


            $('.region-primary-menu').addClass('primary-mobile-menu');

            $('.primary-mobile-menu .menu.-primary > .menu-item').addClass('mobile-menu-item');

            $('.primary-mobile-menu .menu.-primary > .mobile-menu-item').on('click', function() {
                $(this).toggleClass('active');

                console.log('click');
            })
        },

        clear : function() {
            $('.primary-mobile-menu, .mobile-menu-item').removeClass('primary-mobile-menu mobile-menu-item');
        }
    }

    $(document).ready(function() {


        if ($(window).width() < 1180) {
            mobileMenu.init();
        }

        else {
            mobileMenu.clear();
        }
    });



    $(window).on('resize', function(e) {

        var resizeTimer;

        clearTimeout(resizeTimer);
        var resizeTimer = setTimeout(function() {
            if ($(window).width() < 1180) {
                mobileMenu.init();
            }

            else {
                mobileMenu.clear();
            }
        }, 100)
    });



})(jQuery)
kit
  • 1,166
  • 5
  • 16
  • 23
clestcruz
  • 1,081
  • 3
  • 31
  • 75
  • Possible duplicate of [jQuery - how to wait for the 'end' of 'resize' event and only then perform an action?](https://stackoverflow.com/questions/5489946/jquery-how-to-wait-for-the-end-of-resize-event-and-only-then-perform-an-ac) – Jack Bashford Nov 07 '18 at 02:15

2 Answers2

2

It is because of click event being attached in mobileMenu.init(); function. On resize, a new clickevent is getting attached. You can use jQuery.off

$('.primary-mobile-menu .menu.-primary > .mobile-menu-item').off('click').on('click', 
Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59
1

Because in your $(window).on('resize', function (e)... you do this :

 if ($(window).width() < 1180) {
    mobileMenu.init();
 }

And in the mobileMenu.init() function definition you attach an event listener, so whenever you resize the window beneath 1180 size, it's going to attach more event listeners.

 $('.primary-mobile-menu .menu.-primary > .mobile-menu-item').on('click' ...

Anyways the other answer tells you how to remove the event listener, which is what you should do to fix it.

chairmanmow
  • 649
  • 7
  • 20