I am trying to provide a function on an html page with which I can zoom in and out text.
I already tried with all available browsers. Here is my code:
<!DOCTYPE html> <html> <head> <style type="text/css"> #zoomtext { transform: scale(1); transition: transform 0.2s ease-in-out; } </style> <script> window.addEventListener("load", function() { var zoom = 1; var zoomStep = 0.2; }); document.getElementById("zoomIn").addEventListener("click",function(){zoom += zoomStep; document.getElementById("zoomtext").style.transform = "scale("+zoom+")";}); document.getElementById("zoomOut").addEventListener("click",function(){if(zoom > zoomStep){zoom -= zoomStep; document.getElementById("zoomtext").style.transform = "scale("+zoom+")";}}); </script> </head> <body> <button id="zoomOut">-</button> <button id="zoomIn">+</button> <article> <section id="zoomtext"> <p>This is a text that I want to be able to zoom in and out by means of the two buttons indicating plus and minus.</p> </section> </article> </body> </html>
There is no error message. Nothing happens upon click.
script
at end of body
zoom, zoomStep
variables outside eventlistener callback <!DOCTYPE html> <html> <head> <style type="text/css"> #zoomtext { transform: scale(1); transition: transform 0.2s ease-in-out; } </style> </head> <body> <button id="zoomOut">-</button> <button id="zoomIn">+</button> <article> <section id="zoomtext"> <p>This is a text that I want to be able to zoom in and out by means of the two buttons indicating plus and minus.</p> </section> </article> <script> var zoom = 1; var zoomStep = 0.2; document.getElementById("zoomIn").addEventListener("click", function() { zoom += zoomStep; document.getElementById("zoomtext").style.transform = "scale(" + zoom + ")"; }); document.getElementById("zoomOut").addEventListener("click", function() { if (zoom > zoomStep) { zoom -= zoomStep; document.getElementById("zoomtext").style.transform = "scale(" + zoom + ")"; } }); </script> </body> </html>
The issue with your code is that zoom
and zoomStep
are never evaluated. The first event listener just create a function, but the code inside it is never executed.
See a working code here : https://codepen.io/marc-simplon/pen/vqYwYQ?editors=1010
If you need to set the zoom of the whole window, that might not be possible without an external plugin (see Changing the browser zoom level )
If you want to set the zoom for specifically the #zoomtext element, you could use the "zoom" CSS attribute ( https://developer.mozilla.org/en-US/docs/Web/CSS/zoom ), but it is not standard. Another way of handling this would be to increase or decrease the font-size CSS attribute on the #zoomtext element:
document.getElementById("zoomtext").style.fontSize = '12px'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.