Dipak
Dipak

Reputation: 939

Jquery media queries isn't apply without refreshing

I have following code in my page. Background color works perfectly. But I have to refresh to see the change regarding li. If I don't refresh, li has previous effect. Such as in windows screen smaller 500 px, li is shown without clicking.

function myFunction() {
  if ($(window).width() < 500) {
    $('body').css('background', 'black');
    $("nav").click(function() {
      $("li").toggle('slow');
    });
  } else {
    $('body').css('background', 'blue');
    $("li").show();
  }
}

Upvotes: 0

Views: 357

Answers (3)

Pons Purushothaman
Pons Purushothaman

Reputation: 2261

Put your code as a function and call it on onload and on window resize like below

$(window).load(function(){
   //your function
});
$(window).resize(function(){
  //your function
});

Upvotes: 1

Milan Chheda
Milan Chheda

Reputation: 8249

$("nav").click(function() {
  $("li").toggle('slow');
});

function myFunction() {
  if ($(window).width() < 500) {
    $('body').css('background-color', 'black');
  } else {
    $('body').css('background-color', 'blue');
    $("li").show();
  }
}
  1. Instead of background, you should background-color
  2. Secondly, you can have click outside on the function rather than defining it inside.
  3. Assuming, myFunction is triggered/called on resize or load

Upvotes: 1

RacoonOnMoon
RacoonOnMoon

Reputation: 1586

You need to trigger it also on resize, so if you resize the window it will trigger the queries like

$(window).on("load resize",function(){
  //your code goes here
  if ($(window).width() < 500) {
    $('body').css('background', 'black');
    $("nav").click(function() {
      $("li").toggle('slow');
    });
  } else {
    $('body').css('background', 'blue');
    $("li").show();
  }
}

Upvotes: 1

Related Questions