0

I would like to use one if statement. How do I make one if statement?

if ($(window).width() <= 992) {
    //mycode
}

$(window).resize(function () {
    if ($(window).width() <= 992) {
        //mycode
    }
});
siuri
  • 177
  • 1
  • 12

2 Answers2

7

jQuery allows you to assign the event listener to multiple event types.

$(window).on('load resize', function(){
    if ($(window).width() <= 992) {
        //mycode
    }
})
  • I was about to press the submit button with this approach! You beat me to it :D – taxicala Oct 27 '15 at 20:00
  • 5
    Gotta be even quicker to find dupes heh? – Kyll Oct 27 '15 at 20:09
  • 6
    Thank you for answering and contributing to Stack Overflow, however please take a second look at the question, for it seems to be a duplicate. Answering duplicate questions is not such a good idea as it disperses knowledge. – Kyll Oct 27 '15 at 20:12
  • 3
    [The smell](https://chat.stackoverflow.com/transcript/message/26534426#26534426). – Kyll Oct 27 '15 at 20:17
  • 3
    [A wise man once said...](http://chat.stackoverflow.com/transcript/message/25291870#25291870) ;) – Mogsdad Oct 27 '15 at 20:19
0

You could use your existing code, then trigger the resize() event afterwards:

$(window).resize(function () {
    if ($(window).width() <= 992) {
        //mycode
    }
}).resize();
George
  • 34,712
  • 7
  • 55
  • 91