I\'ve written out a very basic script to add/remove a class on load or when a window is resized.
I was just wondering if there was a better way of doing this or if i
Try this. It works for me
function resize() {
if ($(window).width() < 514) {}
else {}
}
$(document).ready( function() {
$(window).resize(resize);
resize();
});
Use Media classes
@media screen and (max-width: 900px) {
.class {
width:800px;
}
}
@media screen and (max-width: 500px) {
.class {
width:450px;
}
}
function resize() {
if ($(window).width() < 514) {
$('html').addClass('mobile');
}
else {$('html').removeClass('mobile');}
}
$(document).ready( function() {
$(window).resize(resize);
resize();
});
Well, I know I'm late to the party, but I saw some things like $(document).ready()
that weren't really necessary.
Try to cache your selectors if you're calling them over and over again, a la var $window = $(window);
This will help with performance. I use a function expression to encapsulate to I stay out of the global scope but still have access to my $window
and $html
cached jQuery selected elements.
(function($) {
var $window = $(window),
$html = $('html');
$window.resize(function resize(){
if ($window.width() < 514) {
return $html.addClass('mobile');
}
$html.removeClass('mobile');
}).trigger('resize');
})(jQuery);
http://jsfiddle.net/userdude/rzdGJ/1
Probably a little cleaner, little easier to follow:
(function($) {
var $window = $(window),
$html = $('html');
function resize() {
if ($window.width() < 514) {
return $html.addClass('mobile');
}
$html.removeClass('mobile');
}
$window
.resize(resize)
.trigger('resize');
})(jQuery);
http://jsfiddle.net/userdude/rzdGJ/2
You Can also Use this Method I think its very clear to follow :
$(window).on('resize', function(){
var win = $(this);
if (win.width() < 514) {
$('html').addClass('mobile');
}
else
{
$('html').removeClass('mobile');
}
});
Simple Method
This issue pestered me for a while, actually. I usually have multiple sizes for transitions. I wrote this an thought I'd share:
$(function() {
var pageTransitions = [['full',1600],['mobile',800],['tiny',400],['micro',0]]; // number shows minimum size - must be from high to low
function resize() {
var target = 0,
w = $(window).width(),
h = $('html');
$.each(pageTransitions, function(index, pageTransition) {
if( w > pageTransition[1]) {
target = index;
return false;
}
});
$.each(pageTransitions, function(index, pageTransition) {
h.removeClass(pageTransition[0]);
});
h.addClass(pageTransitions[target][0]);
}
resize();
jQuery(window).on('resize', function() {
resize();
});
});
http://jsfiddle.net/mckinleymedia/ERZ3q/7/