Search code examples
jqueryresizewindowwidth

Jquery window resizing and click event


i am trying to make responsive web but i got trouble with resizing widow width. when window width is smaller than 885, codes in the first if works fine, however when window width is bigger than 885, it has a problem,,,, even though i block click event(off), when i try to resize again, in console still have "none"and "block" also click event happens and '.common-a' which is clicked has {opacity:0;}.

below is my code.

var $window=$(window);    
    function intoTablet(){    
        var width=$window.width();    
        if(width<=885){    
            $('#wrapping .hidden-gnb .common-ul >li').on('click',function(ee){    
                $(this).siblings().children('.hover-ul-inner').css('display','none');    
                $(this).siblings().children('.common-a').css({'opacity':1});    
                console.log("none");    
                $(this).children('.hover-ul-inner').css('display','table');    
                $(this).children('.common-a').css({'opacity':0});    
                console.log("block");    
            });    
        }    
        if(width>885){    
            $('#wrapping .hidden-gnb .common-ul >li').off('click',function(ee){    
                $(this).siblings().children('.hover-ul-inner').css('display','none');    
                $(this).siblings().children('.common-a').css({'opacity':1});    
                console.log("none");    
                $(this).children('.hover-ul-inner').css('display','table');    
                $(this).children('.common-a').css({'opacity':0});    
                console.log("block");    
            });    
        }    
    }    
    intoTablet();    
    $window.on('resize',function(){    
        intoTablet();    
        console.log("resizing");    
    });    

Solution

  • Use off fuction without callback function like

      $('#wrapping .hidden-gnb .common-ul >li').off('click');
    

    You can add your .css function out of .off() function and the set the opacity

      if(width>885){    
         $('#wrapping .hidden-gnb .common-ul >li').off('click');    
         $(this).children('.common-a').css({'opacity':0});
      }    
    

    Fiddle demo