Home > other >  Combining onload, resize, and window size settings
Combining onload, resize, and window size settings

Time:09-04

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?

CodePudding user response:

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>

CodePudding user response:

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>

  • Related