Switching Stylesheets Based on Browser Width - J Query

You want to change the document’s CSS based on the width of the browser.


There are a few solutions to this problem. One changes the class attribute of the body element, another changes the href attribute of the stylesheet you want to change, and the third includes all size-related stylesheets on the page but enables only one of them at a time.
In each case, we’ll create a function that checks the width of the browser and bind that function to the document’s ready event and to the window’s resize event. The
checkWidth function will then call the setSize function, which we’ll define based on the approach we’re taking:

The definition of the setSize function depends on how you want to switch styles.

Solution 1: Changing the Class on the Body Element

Solution 2: Changing the href Attribute of the Stylesheet That’s Responsible for Size-Related Styling
Let’s assume you have the following size-related stylesheet in your document:

Note that in this case, the new CSS file is requested from the server, which is likely to cause a brief delay in the style change occurring. For this reason, this is perhaps the least-preferable method.

Solution 3: Include All Size-Related Stylesheets in the Page, but Enable Only One at a Time

In this approach, all stylesheets are loaded at page load, and nothing new is fetched when switching from one stylesheet to another. This eliminates the delay caused by solution 2 but it also results in potentially unnecessary HTTP requests if your user is unlikely to need the alternate stylesheets.

There is no definitive answer to which of the three style-switching methods is the best.When choosing a method, you’ll want to consider how likely your users are to need a different stylesheet, how big your size-related stylesheets are, and how you prefer to manage your size-related styles. In many cases, the method from the first solution will be both sufficient and preferable.

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

J Query Topics