0

I am trying to do responsive jQuery, I understand many people suggest using CSS Media Queries, and I do CSS media queries as much as possible, but the things I can do are very limited, and using just CSS Media Queries and/or Boostrap grids has shown their limitations. I am having trouble using $(window).width(). I HAVE searched online for answers, and come across similar questions, but those didn't do the job.

This is my code:

if ( $(window).width() > 480 && $(window).width() < 768) {
   $("html").css("background-color", "red");
} else {
  $("html").css("background-color", "black");
}

The issue is that the screen only stays on a black background color, but doesn't change the background to red when I re-adjust the browser width greater than 480px and below 768px.

1
  • Welcome to Stack Overflow. Are you sure you're using the proper selector? Do you mean $("body").css("background-color", "red"); and $("body").css("background-color", "black"); instead of html? Commented Jan 17, 2019 at 1:18

1 Answer 1

1

I think you just need to call the proper selector: body verus html. Consider the following code:

$(function() {
  $("body").append("<div class='windowWidth'>Window Width: " + $(window).width() + "px</div>");

  function response() {
    if ($(window).width() > 480 && $(window).width() < 768) {
      $("body").css({
        "background-color": "red",
        color: "black"
      });
    } else {
      $("body").css({
        "background-color": "black",
        color: "white"
      });
    }
  }

  response();

  $(window).resize(function() {
    response();
    $(".windowWidth").html("Window Width: " + $(this).width() + "px");
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <p>Paragraph in Body</p>
</div>

Hope that helps.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.