1

I have a javascript function which I want to execute only if the browser screen with is bigger than 1024px.

if ($(window).width() > 1024) {

The problem with this code is that if a user first load the webpage in a browser screen 800px and then just rescale the browser screen to 1024 (or more) the function is not executed. In order to be executed the screen needs to be refreshed.

Do you have any suggestion how to fix it?

tewathia
  • 5,918
  • 3
  • 20
  • 27
user3066588
  • 101
  • 7
  • Use the window `resize` event. See https://api.jquery.com/resize/ – tewathia Apr 05 '14 at 16:07
  • Answered in a jQuery way because you already use jQuery. Normally I would not as it is only tagged JavaScript. But anyhow ... do you want it tagged as javascript or javascript + jQuery? If you are after a pure javascript solution, I'll delete answer. – user13500 Apr 05 '14 at 16:25

4 Answers4

2

Just set the window.resize event, which will be called at least once on load and anytime there is a resize, and use a flag to make sure it isnt executed more than once.

(function(){
   var executed = false;
   $(window).resize(function(){
      if(executed) return;
      if($(window).width()>1024){
         executed = true;
         executeSomeFunc();
      }
   });
})();
Patrick Evans
  • 38,456
  • 6
  • 62
  • 84
0

Use:

  $( window ).resize(function() {
    if ($(window).width() > 1024) {

         // Your code.
    }
 }
Ani
  • 4,241
  • 4
  • 23
  • 29
0

jQuery resize

$(document).ready(function() {
    if ($(window).width() > 1024) {
        my_awesome_window_above1024_function();
    }
});
$(window).resize(function() {
    if ($(window).width() > 1024) {
        my_awesome_window_above1024_function();
    }
});
user13500
  • 3,619
  • 2
  • 24
  • 33
0

I would use native JS for this one like this:

window.onresize=function(){
  if(window.innerWidth > 1024){
    alert('GT 1024');
    // Your function here
  }
};

The width property is innerWidth (http://www.w3schools.com/jsref/prop_win_innerheight.asp) and the resize function is (http://www.w3schools.com/jsref/event_onresize.asp)

Not clear exactly what you want to do, but if you're changing CSS rules for display you're better off using CSS media queries (https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Media_queries)

BenMorel
  • 30,280
  • 40
  • 163
  • 285
amay0048
  • 911
  • 9
  • 11