简体   繁体   中英

Jquery Checkbox uncheck with if statement

I can't quite figure out why my code is not working here.

I have an if statements that checks if 1 or more check boxes have been checked, then if its true a function runs. The function allows a bar to slide down when the page scrolls to a certain height.

It works when I first visit the site after a refresh. ie the bar is not visible, when I scroll, then when I check a box, it becomes visible.

However when I uncheck the box the bar is still visible!

How do I hide it, when the checkbox is unchecked?

I thought a line in the else statement like the below would work, but they don't ( I even tried to add an else if :

$(".userbar").hide(); //OR
$(".userbar").slideUp(); //OR
$(".userbar").off();

Here is my Code:

$(document).on('change', '#est', function (e){
    // Get number of checkboxes checked.
    var counter = $('input[type="checkbox"]:checked').length;
    console.log("Checkboxs checked number: " + counter);
    e.preventDefault();
    if (counter >= 1 ) {
      $(window).scroll(function() {
          if ($(this).scrollTop() < 370)
          {
              $(".userbar").slideUp(100);
          }
          else
          {
              $(".userbar").slideDown(100);
          }
      });
    } else if (counter == 0 ){
            $(".userbar").hide();
          }
});

The first time that counter >= 1 , you bind a function to the window "scroll" event, and that function will decide if the bar will be visible or not. Even if later counter evaluates at zero, and you run the .hide() , the scroll handler you registered before will still be there and run again.

An easy way to fix this would be to add something like

else if (counter == 0 ){
    $(window).off("scroll");
    $(".userbar").hide();
}

Be aware that .off("scroll") will remove any handler for the "scroll" event. If you have others and you want to keep them, you might want to name your handler and remove it individually, like:

function myScrollHandler() {
    if ($(this).scrollTop() < 370)
    {
        $(".userbar").slideUp(100);
    }
    else
    {
        $(".userbar").slideDown(100);
    }
}
// ...
$(window).scroll(myScrollHandler);
// ...
$(window).off("scroll", myScrollHandler);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM