Search code examples
javascriptjqueryresizewindow

How to unbind/off jQuery event when window resize


I am trying to delete a jquery event when the window gets >490. However, the unblind() or off() elements do not deactivate the action activated when the window gets smaller than 490px. Why is this? Does anyone knows any method to make a selection return to its original state?

$(document).ready(function(){

    $(window).resize(function(){
    if ($(window).width()<490) {
    $("#shown").unbind().click(function(){
        event.preventDefault();
        $("body div hidden").toggle('slow');
    });
    }

    else if ($(window).widht()>=490) {
        $("#shown").unbind();
        $("body div hidden").unbind();
    }
    });
});

</script>

Solution

  • Here is how you can achieve your desired, the below code will unbind the hide event based on the screen size.

    $(document).ready(function()
    {
    var eventPresent = false;
    $(window).resize(function()
    {
     console.log("current width : ", $(window).width());
     
    if ($(window).width()<490 && eventPresent == false) 
    { 
     $("#shown").unbind().click(function(event)
     {
       event.preventDefault();   
       $("#divText").toggle('hide');
     });
     eventPresent  = true;
    }    
    else if ($(window).width()>=490 && eventPresent == true) 
    {            
       $("#shown").unbind();
       $("#divText").show()  
       eventPresent = false;     
     }
      });
    });
    
     
     <script   src="https://code.jquery.com/jquery-2.2.4.min.js"   integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="   crossorigin="anonymous"></script>
    
     <a id="shown">click me to hide text</a>
       
    <div id="divText">
                    
    You can not toggle me if screen is more than 490 px wide
             
    </div>
     

    P.S Run the snippet in full page mode.