Hi I wonder if anyone can help, I'm trying to create a responsive site using jQuery (got to do it this way as the target audience is on IE7/8 and css3-mediaqueries.js seems to interfere with jQuery UI that i'm using also). I'm using the following script to detect width and height and apply styles accordingly, it works great for the width but not the height, it loads the SMstyle.css then overwrites with the style.css. I'm trying to learn JavaScript but not super strong at the moment, i know there's got to an easier way! Any help would be appreciated...
function adjustStyle(width) {
width = parseInt(width);
if ((width >= 701) && (width < 1200
)) {
$("#size-stylesheet").attr("href", "css/SMstyle.css");
} else {
$("#size-stylesheet").attr("href", "css/style.css");
}
}
$(function() {
adjustStyle($(this).width());
$(window).resize(function() {
adjustStyle($(this).width());
});
});
function adjustStyle(height) {
height = parseInt(height);
if (height < 800
) {
$("#size-stylesheet").attr("href", "css/SMstyle.css");
} else {
$("#size-stylesheet").attr("href", "css/style.css");
}
}
$(function() {
adjustStyle($(this).height());
$(window).resize(function() {
adjustStyle($(this).height());
});
});
When dealing with responsive layouts, you don't really care about the height. The whole concept is that if the content can't fit with the width, it collapses (and thus increases the height).
EDIT:
I believe you need to use $(document) instead of $(this), since the scope of $(this) will be different when you trigger it manually and when it's triggered by a resize event.
function adjustStyle() {
var width = $(document).width();
var height = $(document).height();
if (((width >= 701) && (width < 1200)) || (height < 800)) {
$("#size-stylesheet").attr("href", "css/SMstyle.css");
} else {
$("#size-stylesheet").attr("href", "css/style.css");
}
}
adjustStyle();
$(window).resize(function() {
adjustStyle();
});
To see the different scopes, try this:
$(function() {
console.log('Scope', $(this)); // Scope is DOM-element
$(window).resize(function() {
console.log('Scope', $(this)); // Scope is Window object.
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With