I want to simuate the zoom In and zoom out events of browser using javascript. Like in MAC you use Command +
to zoom and in Windows Control +
. I want to show the same effect as these commands, so I thought of triggering these using vanilla javascript. But not able to achieve anything till now. Has anyone implemented it?
To simulate the event, I am creating the event of keydown with Command and = (zoomIn in case of Mac), but it is not triggering the zoom event :-
let e = new Event("keydown", {"bubbles": true, "cancelable": true});
e.key = "="; // just enter the char you want to send
e.keyCode = 187;
e.which = e.keyCode;
e.altKey = false;
e.ctrlKey = false;
e.shiftKey = false;
e.metaKey = true;
this.dispatchEvent(e);
To verify, I am listening for the zoom event, the manual browser zoom, and javascript zoom both are going inside the if statement.
document.addEventListener('keydown',function(e) {
if (e.keyCode == 187 && e.metaKey) {
console.log('this is getting triggered');
//debugger;
return true;
}
});
You can try to emulate that behavior with CSS property transform: scale()
<!DOCTYPE html> <html> <head> <style> #test { margin: auto; border: 1px solid black; width: 200px; height: 100px; background-color: white; color: black; } </style> <script> //TODO: Increase scale value by x each time you press button function zoomIn () { document.getElementById("test").style.transform = "scale(1.5)"; } function zoomOut () { document.getElementById("test").style.transform = "scale(0.5)"; } </script> <head> <div id="test"> <p>Test</p> <button onclick="zoomIn()">Zoom IN</button> <button onclick="zoomOut()">Zoom OUT</button> </div> <html>
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.