简体   繁体   中英

Better way to write the following jquery

Im quite new to javaScript/jquery. I wrote the following code to toggle a mobile Navigation but i am quite sure there is a simple way to combine the to following code blocks. i would appreciate advice how to write this a better, sleeker way. Thanks

$(document).ready(function(){
var width = $(window).width();
    if(width <=500){
        $("nav").addClass("mobile").removeClass("desktop");
    }
    else{
        $("nav").removeClass("mobile").addClass("desktop");
    }

});

$(document).ready(function(){
  $(window).resize(function(){
    var width = $(window).width();
    if(width <=500){
        $("nav").addClass("mobile").removeClass("desktop");
    }
    else{
        $("nav").removeClass("mobile").addClass("desktop");
    }
});});

Simply create a single function and call it twice:

function changeClasses() {
    var width = $(window).width();
    if(width <=500){
        $("nav").addClass("mobile").removeClass("desktop");
    }
    else{
        $("nav").removeClass("mobile").addClass("desktop");
    }
}

$(document).ready(changeClasses);
$(window).resize(changeClasses);

maybe better use css media queries...

 @media screen and (max-width: 500px){ .desktop { width: or another rules... } } 

You can make it into a separate function which will clean it up a bit:

function toggleClass() {
    var width = $(window).width();
    if(width <=500) {
        $("nav").addClass("mobile").removeClass("desktop");
    } else {
        $("nav").removeClass("mobile").addClass("desktop");
    }
}

$(document).ready(function(){
    toggleClass();
});

$(window).resize(function(){
    toggleClass();
});

You can always add the event once on resize then trigger the resize event. I added a namespace to the event so that it will not conflict with any other window resize events when we trigger it.

$(window).on('resize.load', function() {
  var isMobile = $(window).width() < 500;
  $("nav").toggleClass("mobile", isMobile).toggleClass("desktop", !isMobile);
}).trigger('resize.load');

https://jsfiddle.net/r6myh0z8/

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