This HTML / JS code :
<script>
window.onload = function(e) {
window.onkeydown = function(event) {
if (event.ctrlKey && (event.keyCode == 61 || event.keyCode == 187))
{
event.preventDefault();
alert("hello");
return false;
}
}
}
</script>
<p>Blah</p>
overrides the browser CTRL+PLUS 's ZOOM keyboard shortcut.
It works on Firefox, Chrome, but not with Safari : with Safari, if you do CTRL+PLUS on this page, the alert("hello")
is launched, but the browser's zooming is also changed !
This means that event.preventDefault();
hasn't worked like it should have worked.
How to use event.preventDefault()
with Safari ?
Note: I already tried as well with StopPropagation, but it doesn't solve the problem.
Seems like this is problem with ctrlKey
. Assuming you use Mac OS X system you need to check for metaKey
too, so your code should be:
if ((event.ctrlKey || event.metaKey) && (event.keyCode == 61 || event.keyCode == 187))
We probably have different keyboard layouts or something, but my +
and -
signs on my numpad have the key code values 107 and 109. (http://www.asquare.net/javascript/tests/KeyCode.html)
The code snippet below works in safari for me.
window.onkeydown = function (event) {
if (event.ctrlKey && (event.keyCode == 107 || event.keyCode == 109)) {
event.preventDefault();
alert("hello");
}
}
You can try this:
window.onkeydown = function(event) {
if (event.ctrlKey && (event.keyCode == 61 || event.keyCode == 187))
{
if (event.preventDefault){
event.preventDefault();
}
else {
event.returnValue = false;
}
alert("hello");
return false;
}
}
}
The key codes for zoom are different across browsers:
Opera MSIE Firefox Safari Chrome
61 187 107 187 187 = +
109 189 109 189 189 - _
Also try :
event.stopImmediatePropagation();
To prevent other handlers from executing.