简体   繁体   中英

Execute functions only if a condition is true

I only want to fire functions if a condition (specifically, my window size) is true. My code looks like this:

$(window).resize(function() {
    console.log("window resized");
    if ($(window).width() > 769) {
      $('.panel').hover(
        function() {
          $(this).children('.initial').addClass('hide');
          $(this).children('.hover').addClass('show');
        }, function() {
        $(this).children('.initial').removeClass('hide');
        $(this).children('.hover').removeClass('show');
      }
      );
    } else {
        return false;
    }
  });

The function is a hover function that hides panel upon hover. The expected behavior/goal is that once I go below 769 pixels, the function will not execute, and when you hover the panels will remain visible. I was trying to do this by returning false on my else condition.

After further research, return: false; is similar to e.preventDefault(); as it prevents the default actions from taking place as well as events from bubbling.

How would be best to go about blocking these functions from firing based on window size? My other concern is performance - as can be seen, for every pixel the window is resized, the function is fired!

I already checked out and tried variations of JavaScript Allow various functions to execute only if some condition is true but I didn't find it helpful.

You're not conditionally executing the action, you're conditionally assigning the event handler . And once it's been assigned, it's going to run every time. All you're doing is re-assigning the same event handler many times whenever the window is resized.

Instead, assign the event handler once so that it always applies, and then check the condition inside the event handler. Something like this:

$('.panel').hover(
    function() {
        if ($(window).width() > 769) {
            $(this).children('.initial').addClass('hide');
            $(this).children('.hover').addClass('show');
        }
    }, function() {
        if ($(window).width() > 769) {
            $(this).children('.initial').removeClass('hide');
            $(this).children('.hover').removeClass('show');
        }
});
$('.panel').hover(

This logic is creating bindings on the element that happen later when the user hovers on the element. This is after which point, completely independent of the window size. If you don't want the hover to happen in some cases, that logic needs to be inside your hover logic, not just the resize.

And fwiw, repeating the hover bindings inside a scroll event handler isn't the best practice and is most likely creating many many duplicate bindings.

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