0

I'm trying to make a script only work when the user is in 1024 or less. It works somewhat okay, if the user don't resize the window. But when i fire the click event on lower than 1024 and then resize to lets say 1200 the toggle classes have been added and the animation trickers again.

Any suggestions?

if ($(window).width() <= 1024) {
    $("#primary-menu").click(function(){
        $(".main-navigation").removeClass("toggled");
        $(".cmn-toggle-switch").removeClass("active");
        $(".menu-item").toggleClass("animated").toggleClass("wow").toggleClass("fadeInUp");
    });

    $(".hamburger-menu-text").click(function(){
        $(".cmn-toggle-switch").toggleClass("active");
        $(".main-navigation").toggleClass("toggled");
        $(".menu-item").toggleClass("animated").toggleClass("wow").toggleClass("fadeInUp");
    });     
};
Mikkel Madsen
  • 347
  • 2
  • 5
  • 17
  • Consider to use `window.matchMedia()` method to avoid any bug https://developer.mozilla.org/en/docs/Web/API/Window/matchMedia That's said, it sounds like you would just need to use CSS media queries – A. Wolff May 07 '15 at 12:37

2 Answers2

3

use if statement inside the click event

 $("#primary-menu").on('click',function(){
     if ($(window).width() <= 1024) {
        //..........
     }else{
        //..........
     }
});
Mohamed-Yousef
  • 23,946
  • 3
  • 19
  • 28
0

Check the window width on document ready and on window resize, and assign or remove the click listener:

var primaryFunc = function() {
    $(".main-navigation").removeClass("toggled");
    $(".cmn-toggle-switch").removeClass("active");
    $(".menu-item").toggleClass("animated").toggleClass("wow").toggleClass("fadeInUp");
}

var hamFunc = function() {
    $(".cmn-toggle-switch").toggleClass("active");
    $(".main-navigation").toggleClass("toggled");
    $(".menu-item").toggleClass("animated").toggleClass("wow").toggleClass("fadeInUp");
} 

var resetElements = function() {
   // Unbind the click event
   $("#primary-menu").off('click');
   $(".hamburger-menu-text").off('click');

   // remove assigned classes from elements
}

var checkWin = function() {
   var w = $(window).width();
   if (w <= 1024) {
       $("#primary-menu").on('click', function() {
          primaryFunc();
       });
       $(".hamburger-menu-text").on('click', function() {
          hamFunc();
       });
   } else {           
       resetElements();
   }
}

Execute checkWin() on dom ready and on window resize:

$(document).ready(function() {
    checkWin();
})

$(window).resize(function() {
    checkWin();
});
kapantzak
  • 11,610
  • 4
  • 39
  • 61