Disable / enable scrolling with JQuery

3

I need an area that when clicked, prevents scroll of the screen while the cursor is over that area, however, it works normal outside that area. I have achieved this with a function that I will leave next, but when I click the close button, I need the previous function to be canceled.

$('#el').click(function(){
    
$(this).on({
    'mousewheel': function(e) {
        e.preventDefault();
        e.stopPropagation();
    }
})

});
body {
    height: 2700px;
}
#el {
    position: relative;
    width: 250px;
    height: 250px;
    background: red;
}
#close {
    position:absolute;
    color:#fff;
    cursor:pointer;
    background:rgba(0,0,0,0.3);
    right:0;
    border:0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id='el'>
    <button id='close'>x</button>
</div>
    
asked by anonymous 22.04.2015 / 15:01

2 answers

3

You can use is(":visible") , I believe that when the window closes you use display: none , try:

$('#close').click(function() {
    $('#el').fadeOut();
});

$('#el').click(function() {
    var $this = $(this);
    $this.on({
        'mousewheel': function(e) {
            if ($this.is(":visible")) {
              e.preventDefault();
              e.stopPropagation();
            }
        }
    });
});
body {
    height: 2700px;
}
#el {
    position: relative;
    width: 250px;
    height: 250px;
    background: red;
}
#close {
    position:absolute;
    color:#fff;
    cursor:pointer;
    background:rgba(0,0,0,0.3);
    right:0;
    border:0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id='el'>
    <button id='close'>x</button>
</div>
    
22.04.2015 / 15:11
2

To do a toggle you can use a variable like in the example:

var scroll = true; // Define como scrol habilitado

$('#el').click(function(){
   scroll = !scroll; // Ao clicar, troca de true pra false, ou false para true
    
   $(this).on({
      'mousewheel': function(e) {
         if (!scroll){ // Verifica se o scroll está DESABILITADO ou seja FALSE
            e.preventDefault();
            e.stopPropagation();
         }
       }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id='el'>
    <button id='close'>x</button>
</div>
    
22.04.2015 / 15:19