Alvarez
Alvarez

Reputation: 1333

How to manipulate the screen width via js?

I'll try to explain my use case here. In my site I have a break point for desktop view, and break point for tablet view (which is more compact). I'm trying to add a function to allow seeing the tablet view when browsing from desktop, cause some members prefer the compact design in their desktop as well.

For doing that, I figured I would need to trick the '@media(max-width:X)' query. I'm looking for a JS code that can manipulate the screen width value, so when the browser calculates max-width, it would be against a value that I specified.

One thing to note, this is suppose to work on desktop browsers, so the meta viewport can't be used here.

Upvotes: 1

Views: 242

Answers (1)

user1585455
user1585455

Reputation:

One solution is to apply a specific class (e.g: .tablet) to the body.

<body class="tablet"></body>

In your CSS:

@media screen and (/* your query */) {
   .tablet .my-class {
        /* tablet specific stuff */
    }
}

You could then remove the .tablet class and replace it with .desktop via JavaScript

var body = document.body;

var switchToDesktop = function() {
    body.className = body.className.replace('tablet', 'desktop');
}

var switchToTablet = function() {
    body.className = body.className.replace('desktop', 'tablet');
}

var toggleView = function() {
    (body.className.indexOf("tablet") > -1) ?
        switchToDesktop() :
        switchToTablet();
}

If you are using SASS or LESS, you can nest the tablet-specific styles.

@media screen and (/* your query */) {
   .tablet {
        h1 {
            /* tablet specific h1 */
        }
        .my-div {
            color: red;
        }
        /* etc... */
    }
}

Upvotes: 3

Related Questions