Note that there are some explanatory texts on larger screens.

plurals
  1. POjQuery : Add class dynamically depending on the browser window resolution
    text
    copied!<p>Hello friends I am trying to add a class to body dynamically depending on the browser window resolution. Here is the code I am trying to use but need help tuning it as I dont know jQuery at all. </p> <p>The options I want to achieve are :</p> <p>Once a visitor comes to my site, this code must check his browser windows size and add class to body as per the following rules</p> <ol> <li><p>If window size is <strong>more than</strong> 1024px <strong>but less than</strong> 1280px then add class <code>.w1280</code>.</p></li> <li><p>If window size is <strong>more than</strong> 1280px <strong>but less than</strong> 1440px then add class <code>.w1440</code>.</p></li> <li><p>If window size is <strong>more than</strong> 1440px <strong>but less than</strong> 1280px then add class <code>.w1680</code>.</p></li> <li><p>If window size is <strong>more than</strong> 1680px then add class <code>.wLarge</code>.</p></li> </ol> <p>To achieve this, I am trying to use the following script. My questions are:</p> <ol> <li><p>Is this the <strong>correct code</strong>? If not what is the correct code?</p></li> <li><p>Is this the best <strong>shortest possible</strong> code? If not what will be the correct code?</p></li> </ol> <p>Kindly help as my knowledge of jQuery is almost ZERO.</p> <pre><code>function checkWindowSize() { if ( $(window).width() &gt; 1024) { $('body').addClass('w1280'); } else { $('body').removeClass('w1280'); } if ( $(window).width() &gt; 1280 ) { $('body').addClass('w1440'); } else { $('body').removeClass('w1440'); } if ( $(window).width() &gt; 1440) { $('body').addClass('w1680'); } else { $('body').removeClass('w1680'); } if ( $(window).width() &gt; 1600) { $('body').addClass('wLarge'); } else { $('body').removeClass('wLarge'); } } checkWindowSize() </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload