4

In my CSS file I have this:

@media (max-width: 480px) {
  div {
     background: red;
  }
}

Emulate with javascript

Is there a way to emulate 480px device width with Javascript? I'm thinking of a button with click event to make the CSS beleve the device with is max 480px width.

I will be using jQuery for it if it's possible to emulate media queries.

Jens Törnell
  • 23,180
  • 45
  • 124
  • 206
  • Curious...what would be the purpose? – Paulie_D Mar 07 '14 at 12:44
  • i think there is no possibility beside resizing the window – Dominik Goltermann Mar 07 '14 at 12:45
  • put it inside an iframe – nakajuice Oct 21 '18 at 15:10
  • My purpose would be a live example of a responsive layout, in a developer documentation. I want the reader to be able to test different viewport sizes and see how the demonstrated layout reacts. I'll have to recommend the browser's device preview tools here. Or I'll fake it with additional CSS classes with the same rules as the media query that I can add or remove from the resize script. – ygoe Apr 19 '22 at 22:44

2 Answers2

2

You can set the viewport manually in JS, which could be the solution. This SO question covers it Dynamic viewport

Set the content attribute to include a width parameter:

document.getElementById("viewport").setAttribute("content", "width=1024, initial-scale=0, maximum-scale=1.0, minimum-scale=0.25, user-scalable=yes");

from http://www.wearecube.ch/how-to-do-responsive-optout-by-setting-the-view-port-with-javascript-or-ruby-on-rails/

Community
  • 1
  • 1
Dylan Valade
  • 5,565
  • 6
  • 42
  • 56
  • Great idea! However it did not work in Google Chrome that I'm using. Right now I use http://app.protofluid.com/ until I found out any beter way to do it. – Jens Törnell Mar 07 '14 at 14:49
-3

Hit F12, then go to the Emulation tab (IE), open the Console drawer and click Emulation (Chrome), or whatever browser you are using's equivalent.

Here you can emulate whatever screen or device specifications you want to test with.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592