0

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?

Anna_B
  • 820
  • 1
  • 4
  • 23
  • You should be more clear, what is "doesn't work like expected"? What does it do instead? – Jess Sep 03 '22 at 23:30
  • Does this answer your question? [JQuery .on() method with multiple event handlers to one selector](https://stackoverflow.com/questions/8608145/jquery-on-method-with-multiple-event-handlers-to-one-selector) – Jess Sep 03 '22 at 23:36

2 Answers2

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>
Jess
  • 177
  • 5
0

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>
SirPilan
  • 4,649
  • 2
  • 13
  • 26