Simulate a (Ctrl ) + (-) zoom out event using Javascript
Simulate a (Ctrl ) + (-) zoom out event using Javascript
How do we simulate a Ctrl - zoom out using Javascript? The style zoom property or the transform property seems to zoom out but differently with white space in the corners and not like how your typical Ctrl - zoom out on your browser would look like.
Through Javascript I tried the KeyboardEvent but it does not do the trick
var event = new KeyboardEvent("keypress", key:"-", code:45 ,ctrlKey:true);
document.body.dispatchEvent(event);
Thanks.
Yes that's because I want my page to be atleast 1920px wide with occupying the entire width of the browser and that seems to be only possible when you zoom out using browser in low resolution screens
– Kiran Baktha
Sep 6 '18 at 17:21
Are you trying to substitute responsiveness with emulating a zoom? Because I would definitely advise against that, but let me answer your question here.
– CodeSpent
Sep 6 '18 at 17:23
2 Answers
2
I'm not sure if you're set on using Javascript, so I'll leave a CSS option for you here as well. CSS has an accessibility feature appropriately called Zoom which will do what you're asking.
div
zoom: 200%
As far as actually emulating the button press, though, try this;
var event = jQuery.Event("keydown");
event.which = 107; // Key code for +
event.ctrlkey = true;
$(document).trigger(event);
developer.mozilla.org/en-US/docs/Web/CSS/zoom + triggering a keydown event doesn't emulate actual key strokes, it just executes the keydown listener(s) if attached.
– Teemu
Sep 6 '18 at 17:54
Yup it does...is there a way to emulate actual key strokes?
– Kiran Baktha
Sep 6 '18 at 18:22
You are mis-using the key attribute. Use e.g. this instead:
var event = new KeyboardEvent('keydown', key: 'Minus' );
Here's a link to the list of values for KeyboardEvent.key
.
KeyboardEvent.key
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Is there a particular reason you want to emulate the browser zoom itself as opposed to just zooming in on the elements?
– CodeSpent
Sep 6 '18 at 17:19