resize - jQuery : Add class dynamically depending on the browser window resolution -


hello friends trying add class body dynamically depending on browser window resolution. here code trying use need tuning dont know jquery @ all.

the options want achieve :

once visitor comes site, code must check browser windows size , add class body per following rules

  1. if window size more than 1024px but less than 1280px add class .w1280.

  2. if window size more than 1280px but less than 1440px add class .w1440.

  3. if window size more than 1440px but less than 1280px add class .w1680.

  4. if window size more than 1680px add class .wlarge.

to achieve this, trying use following script. questions are:

  1. is correct code? if not correct code?

  2. is best shortest possible code? if not correct code?

kindly knowledge of jquery zero.

function checkwindowsize() {       if ( $(window).width() > 1024) {          $('body').addclass('w1280');           } else {           $('body').removeclass('w1280');       }      if ( $(window).width() > 1280 ) {          $('body').addclass('w1440');           } else {           $('body').removeclass('w1440');       }      if ( $(window).width() > 1440) {          $('body').addclass('w1680');           } else {           $('body').removeclass('w1680');       }      if ( $(window).width() > 1600) {          $('body').addclass('wlarge');           } else {           $('body').removeclass('wlarge');       }  }     checkwindowsize() 

if aren't storing other classes on body element, this:

function checkwindowsize() {     var width = $(window).width();     document.body.classname = width > 1600 ? 'wlarge' :                               width > 1440 ? 'w1680' :                               width > 1280 ? 'w1440' :                               width > 1024 ? 'w1280' : ''; } 

some people might advise switch statement, then, people eat young.

this function overwrite body's class every time it's called (the default, if browser smaller than/equal 1024 pixels, no class @ all), said won't work if body has other classes need maintained.

edit per Šime's suggestions, here's safer way it:

function checkwindowsize() {     var width = $(window).width(),     new_class = width > 1600 ? 'wlarge' :                 width > 1440 ? 'w1680' :                 width > 1280 ? 'w1440' :                 width > 1024 ? 'w1280' : '';      $(document.body).removeclass('wlarge w1680 w1440 w1280').addclass(new_class); } 

Comments

Popular posts from this blog

java - SNMP4J General Variable Binding Error -

windows - Python Service Installation - "Could not find PythonClass entry" -

Determine if a XmlNode is empty or null in C#? -