Sometimes we need to format the content differently according to the screen resolution of the user. One of the ways to do this is to simply detect the screen width using the screen.width property and change the stylesheet. In this tutorial we're going to see how to do that using jQuery.

The first step is to load our base stylesheets, the jQuery library and our javascript.

The colour of this text will change.

Let's test if the user screen size is less than 1024×768 and if it is, we will change the stylesheet.

The changing style

Define the same style in two different sheets. Once for the 1024 x 768 and once for the 800 x 600. Just make something quick and distinctive, for style1.css I'm adding:

div{
color: #006699;
font: 24px Georgia, serif;
}


and for style2.css
 

div{
color: #df0000;
font: 24px "Trebuchet MS", sans-serif;
}


 

Detecting screen width

We are going to add a JavaScript alert so the execution will pause until we click OK and we get to see the former style.
 

$(document).ready(function() {

if ((screen.width>=1024) && (screen.height>=768)) {
alert('Screen size: 1024x768 or larger');
$("link[rel=stylesheet]:not(:first)").attr({href : "style2.css"});
}
else {
alert('Screen size: less than 1024x768, 800x600 maybe?');
$("link[rel=stylesheet]:not(:first)").attr({href : "style1.css"});
}
});


As a selector, we look for the link element with a rel attribute with a value of stylesheet. We are going to redirect its href to a different stylesheet. Now, since I'm loading a reset stylesheet in the first place, i will add the :not(:first) modifier, so it won't affect the first element.
 

Enjoy!

 

0 Shares:
Leave a Reply

Your email address will not be published. Required fields are marked *

five × 3 =

This site uses Akismet to reduce spam. Learn how your comment data is processed.

You May Also Like

QUOjs – Micro JavaScript Library

QuoJS is a micro, modular, Object-Oriented and concise JavaScript Library that simplifies HTML document traversing, event handling, and Ajax interactions for rapid mobile web development. It allows you to write powerful, flexible and cross-browser code with its elegant, well documented, and micro coherent API.

CSS-Only Tooltips With Hint.css

Hint.css is a tooltip library that is built with SASS and only uses CSS + HTML. The library uses data attribute, content property, pseudo elements and CSS3 transitions.

5+ Great Responsive CSS Frameworks

Using responsive CSS frameworks developers can speed up the delivery and improve the quality of responsive CSS code. Since responsive web design is in high demand a lot of frameworks have been created to streamline the delivery of high quality mobile-ready websites.