user5716144
user5716144

Reputation:

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");
    }
});});

Upvotes: 1

Views: 64

Answers (4)

Sean Wessell
Sean Wessell

Reputation: 3510

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/

Upvotes: 0

Ivan Karaman
Ivan Karaman

Reputation: 1234

maybe better use css media queries...

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

Upvotes: 3

baao
baao

Reputation: 73231

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);

Upvotes: 4

APAD1
APAD1

Reputation: 13666

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();
});

Upvotes: 1

Related Questions