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?

2
  • Use the window resize event. See api.jquery.com/resize Commented Apr 5, 2014 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. Commented Apr 5, 2014 at 16:25

4 Answers 4

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();
      }
   });
})();
Sign up to request clarification or add additional context in comments.

Comments

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();
    }
});

4 Comments

And down-vote was because of?
But now the problem is that it is not working on "document ready" - what I mean is when I load the page I need to resize it before the function can be executed e.g If my browser screen is 1050px the function won't work before I resize the screen.
@user3066588: Like that?
@user3066588: Glad to be at service :)
0

Use:

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

         // Your code.
    }
 }

1 Comment

Anyone care to explain the down vote?
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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.