Reputation: 6552
I would like to give users the ability to increase/decrease the rendering size of the content inside of a web app.
The CTRL+ and CTRL- features (or CTRL1 through CTRL9) of Chrome & Firefox are handy - but is there a way from JavaScript to execute those features?
Clarification: I want the user to be able to achieve this via mouse-clicks, not keypresses, so something like this:
function resize_rendering() {
// code that executes ctrl+ or crtl-
}
Upvotes: 4
Views: 2328
Reputation: 1
Look towards CSS property "zoom"
/* ctrl++ */
body {
zoom: 1.1;
}
For JS, it's like:
function resize_rendering(zoom) {
let currentZoom = parseFloat(document.body.style.zoom) || 1
document.body.style.zoom = currentZoom * zoom
}
resize_rendering(1.1) // ctrl++
resize_rendering(0.9) // ctrl+-
Upvotes: 0
Reputation: 168685
The browser zoom level is a user setting, which is there for accessiblity purposes; it's not intended for the site developer to ever know or care what the zoom level is, so I would expect that you'll have trouble doing exactly what you want. Certainly, it'll be hard to get it right in a way that works cross-browser.
The normal approach to this is to have a sizing gadget that changes the base font size.
If all the font sizes in your site are in em
units, then you can change the sizes of all the text on the site with a single CSS change.
So you would have a set of buttons on the site which use Javascript to set the font-size
of the <body>
element to (for example) 12, 14, 16 or 18 pixels, depending on the element clicked.
There's a write-up of the technique here: http://labnol.blogspot.com/2006/12/allow-site-visitors-to-change-font.html
Upvotes: 3
Reputation: 63812
You are not allowed to by design. You can't change a user's browser setting via Javascript.
You can do other things, like modify all of the CSS on your page to scale everything down to simulate a CTRL-
, but that's all.
In some browsers you can capture CTRL+/- before the browser does, allowing you to stop those events from occuring. But you cannot do the oppisite - you cannot cause those events to occur from your own script.
Upvotes: 1
Reputation: 38005
You could intercept the keystroke in a general key event handler (such as on the window
object), check to see if it's the one you're looking for, and if so, call stopPropagation()
on the event parameter (and return false) to prevent the browser from then handling it on its own.
You'd then have to perform the sizing operation yourself, such as by modifying a stylesheet using JavaScript.
window.addEventListener( 'keydown', function( e ) {
if ( /* check e.keyCode etc. */ ) {
// modify global style to increase/decrease font size
e.stopPropagation();
return false;
} );
Upvotes: 0
Reputation: 8768
This library here by John Resig is a jQuery plugin that should do the job. There's some samples. Its quite easy to hookup combinations of keys as well.
Upvotes: 0