简体   繁体   中英

jQuery if width is less than 767 the previous code should not work

Problem: I want that the code in the if statement would work only if the screen width is greater than 767px, and if it is less than 767px the previous code shouldn't work, how to do it?

jQuery:

$(document).ready(function() {
    $(window).resize(function() {
        if ($(document).width() > 767) {
    $('.navigation-hide').hide();

   $("nav").mouseenter(function() {    
       $('.navigation-hide').stop().fadeIn(500);       
   });

   $('nav').mouseleave(function() {    
        $('.navigation-hide').stop().fadeOut(500);         
   });
}
        else {
            break;
        }
    });

});

It's not a good idea to use JS in this way.

You can use CSS to show/hide elements depending on screen size using media queries .

@media (max-width: 768px) {
  .navigation-hide {
      display: none;
  }
  nav:hover .navigation-hide {
      display: block;
  }
}

You can use CSS transitions to achieve the fade effect.

Check out this jsFiddle

.navigation-hide {
    position: absolute;
    left: -999em;
    top: 0;
    opacity: 0;
    transition: opacity 0.5s, left 0.5s 0.5s;
}

nav:hover .navigation-hide {
    left: 0;
    opacity: 1;
    transition: opacity 0.5s;
}

It should be achieved using CSS's media queries and effects, see this https://jsfiddle.net/DTcHh/12782/

however if you insist using jQuery, then check this out

$(document).ready(callbackReady);
$(window).resize(callbackResize);

var isWidthReady = false;
var callbackReady = function() {
    $("nav").mouseenter(function() {
        if(isWidthReady) {
            $('.navigation-hide').stop().fadeIn(500);     
        }           
    });
    $('nav').mouseleave(function() {
        if(isWidthReady) {
            $('.navigation-hide').stop().fadeOut(500);  
        }
    });
}
var callbackResize = function() {
    if ($(document).width() > 767) {
        $('.navigation-hide').hide();
        isWidthReady = true;
    }
    else {
        isWidthReady = false;
    }
};

Note: do not implement any event handler inside another recurring event (resize() in your case) unless you are creating a new element dynamically or removing and reattaching an event.

Use an if statement with window.innerWidth!

    $(document).ready(function() {
if(window.innerWidth >= 767){
 $(window).resize(function() { if ($(document).width() > 767) { $('.navigation-hide').hide(); $("nav").mouseenter(function() { $('.navigation-hide').stop().fadeIn(500); }); $('nav').mouseleave(function() { $('.navigation-hide').stop().fadeOut(500); }); } else { break; } }); }});

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