Skip to content

Instantly share code, notes, and snippets.

@danny-englander
Created September 13, 2012 00:16
Show Gist options
  • Star 19 You must be signed in to star a gist
  • Fork 14 You must be signed in to fork a gist
  • Save danny-englander/3710930 to your computer and use it in GitHub Desktop.
Save danny-englander/3710930 to your computer and use it in GitHub Desktop.
JQuery Responsive Classes
/*
* Inspired by:
* http://designedbythomas.co.uk/blog/how-detect-width-web-browser-using-jquery
*
* This script is ideal for getting specific class depending on device width
* for enhanced theming. Media queries are fine in most cases but sometimes
* you want to target a specific JQuery call based on width. This will work
* for that. Be sure to put it first in your script file. Note that you could
* also target the body class instead of 'html' as well.
* Modify as needed
*/
(function( $ ){
$(document).ready(function(){
var current_width = $(window).width();
//do something with the width value here!
if(current_width < 481)
$('html').addClass("m320").removeClass("m768").removeClass("desktop").removeClass("m480");
else if(current_width < 739)
$('html').addClass("m768").removeClass("desktop").removeClass("m320").removeClass("tablet");
else if (current_width < 970)
$('html').addClass("tablet").removeClass("desktop").removeClass("m320").removeClass("m768");
else if (current_width > 971)
$('html').addClass("desktop").removeClass("m320").removeClass("m768").removeClass("tablet");
if(current_width < 650)
$('html').addClass("mobile-menu").removeClass("desktop-menu");
if(current_width > 651)
$('html').addClass("desktop-menu").removeClass("mobile-menu");
});
//update the width value when the browser is resized (useful for devices which switch from portrait to landscape)
$(window).resize(function(){
var current_width = $(window).width();
//do something with the width value here!
if(current_width < 481)
$('html').addClass("m320").removeClass("m768").removeClass("desktop").removeClass("tablet");
else if(current_width < 669)
$('html').addClass("m768").removeClass("desktop").removeClass("m320").removeClass("tablet");
else if (current_width < 970)
$('html').addClass("tablet").removeClass("desktop").removeClass("m320").removeClass("m768");
else if (current_width > 971)
$('html').addClass("desktop").removeClass("m320").removeClass("m768").removeClass("tablet");
if(current_width < 650)
$('html').addClass("mobile-menu").removeClass("desktop-menu");
if(current_width > 651)
$('html').addClass("desktop-menu").removeClass("mobile-menu");
});
})( jQuery );
@RyanBrackett
Copy link

Hey man, I love the code! I rewrote it as one function to eliminate the redundant editing.

https://gist.github.com/RyanBrackett/6107983

~ RB

@sepehr
Copy link

sepehr commented May 14, 2015

Might come handy: http://restivejs.com/

@fahreza007
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment