skip to Main Content

I would like to show something only if the window size is bigger than 1000px. It should work on load, and if the window size changes.

This is my try:

$(window).on("resize", function() {
  if ($(window).width() > 1000) {
    alert("Hello!");
  });
}
}).resize();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Unfortunately, it doesn’t work like expected. What should be changed?

2

Answers


  1. To make a function run on both load and resize, you can name both load and resize in the parameter for "on".

    $(window).on("resize load", () => {
        alert("Hello!")
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    Login or Signup to reply.
  2. You are close. Just modify the code as metioned below.

    $(window).on("resize", function() {
      if ($(window).width() > 1000) {
        alert("Hello!");
      });  // <- remove this
    }      // <- indent this (+2 spaces)
    }).resize();
    

    This is a good example why indentation is important. As soon as you see 2 } in the same column you know something isnt right – which is the case in the last 2 rows.

    Working example:

    $(window).on("resize", function() {
      $('#size').html('Size: ' + $(window).width());
      if ($(window).width() > 300) {
        $('#result').html('> 300');
      } else {
        $('#result').html('<= 300');
      };
    }).resize();
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <div id="size"></div>
    <div id="result"></div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search