I have JavaScript code that listens to the "return" key pressed,
works on all browsers except webkit browsers.
I am aware of webkits recent changes to keyboard event handling.
I cant find the right solution in this detailed explanation.
Here is the code:
function addEventHandler(node,type,fn){
if(typeof window.event !== "undefined"){
/* Internet Explorer way */
node.attachEvent( "on" + type, fn );
} else {
/* FF & Other Browsers */
node.addEventListener( type, fn,false );
}
}
function detectSubmit(){
searchTextInput = document.getElementById("txtSearch")
addEventHandler(searchTextInput,"keydown",triggerSearch);
}
function triggerSearch(e){
//getting the character that was pressed cross browser.
var key = e.keycode ? e.keycode : e.which;
//detect if the return key was pressed.
if(key==13){
alert("return clicked");
}
}
addEventHandler(window,"load",detectSubmit);
The most obvious thing is the simple typo on the following line:
var key = e.keycode ? e.keycode : e.which;
It should be keyCode rather than keycode.
Other than that, there are problems in the addEventHandler function. I suggest the following:
function addEventHandler(node,type,fn){
if (typeof node.addEventListener !== "undefined"){
/* DOM-compliant method */
node.addEventListener( type, fn,false );
} else if (typeof node.attachEvent !== "undefined") {
/* IE */
node.attachEvent( "on" + type, fn );
}
}
Two things: first, it's better to check for attachEvent directly rather than infer its existence from the existence of window.event. In fact, window.event exists in Safari and Chrome but not (I think) attachEvent, so that dodgy inference is preventing your code from working.
Secondly, it's better to check for the DOM standard addEventListener first and use it where it exists rather than attachEvent. Opera, for example, has both but only addEventListener is standardised.
Related
I have difficulty on integrating my JavaScript syntax. My code is working on Internet Explorer (IE). However, I encountered a JavaScript error when running it on Safari.
This is my test code:
document.onmouseup = function hideaddrspopup () {
if (event.srcElement.id != 'fieldName') {
alert(event.srcElement.id);
}
}
I tried something like:
document.onmouseup = function hideaddrspopup() {
if (event.srcElement.id != 'fieldName' || event.target.id != 'fieldName') {
alert(event.srcElement.id);
alert(event.target.id);
}
}
But still an error is appearing on the console:
'TypeError: 'null' is not an object (evaluating 'event.target')'
I am aware that event.scrElement is only working in IE. How to make it work on the other browsers?
According to MDN:
This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.
Event.srcElement is a proprietary alias for the standard Event.target property. It is specific to old versions of Microsoft Internet Explorer.
So just avoid using event.srcElement instead you should use event.target.
As Bhojendra mentioned don't use srcElement. Check for object null or not before accessing id or target property as below.
document.onmouseup = function hideaddrspopup ()
{
if (e && e.target && e.target.id!='fieldName')
{
alert(e.target.id);
}
else if(e && e.srcElement && e.srcElement.id!='fieldName')
{
alert(e.srcElement.id);
}
}
Updated with else if to support older IE browser. target should support it too but you could test without else part if it is necessary or not.
You're missing the event variable in your function
document.onmouseup = function hideaddrspopup (event)
{
if (event.srcElement.id != 'fieldName' || event.target.id != 'fieldName')
{
alert(event.srcElement.id);
alert(event.target.id);
}
}
I am working on an application where there are a lot key shortcuts for replication certain UI actions. One of such key shortcut combination is Alt + s
document.body.addEventListener('keyup',keyUpHandler,false);
function keyUpHandler(e)
{
e.stopPropagation();
var key = e.which || e.keyCode;
cellKeys(e,key);
}
function cellKeys(e,key){
if (e.altKey && key === 83) document.getElementById('saveCell').dispatchEvent(mouseclick); //alt + s
}
This key combination seems to work great for all other browsers except Mozilla firefox as this shortcut is used by the browser to open up history menu on top of the page.
I am looking for some workaround for this problem.
PS: I cannot use key down event listener and I have to use the same key combination. Also using e.preventDefault() was futile.
Be aware that some browsers will not allow you to capture certain shortcuts! A working example for the Alt+s shortcut in Mozilla Firefox:
window.onkeydown = function(e){
if(e.altKey && e.keyCode == 83){
e.preventDefault();
alert("Shotcut Pressed")
}
}
I have a Flex app running on a web page, and I want to use the Command+← key combination to trigger certain actions in the app. This is fine on most browsers, but on Safari, the browser intercepts this keyboard event and causes the browser "back" event instead. Is there a way, either through Flex or via JavaScript elsewhere on the page, that I can tell Safari not to do that?
Short answer, it's a (little) known bug on non-mac versions of safari. You can't reliably block all shortcut keys. Perhaps if you were more specific about what other shortcuts you're trying to block? Maybe some of them will work. e.g. cut paste copy have their own special methods of blocking. (Although it seems like you probably already know that.)
Are you using something like this?
function blockKeys(e) {
var blocked = new Array('c','x','v');
var keyCode = (e.keyCode) ? e.keyCode : e.which;
var isCtrl;
if(window.event)
isCtrl = e.ctrlKey
else
isCtrl = (window.Event) ? ((e.modifiers & Event.CTRL_MASK) == Event.CTRL_MASK) : false;
if(isCtrl) {
for(i = 0; i < blocked.length; i++) {
if(blocked[i] == String.fromCharCode(keyCode).toLowerCase()) {
return false;
}
}
}
return true;
}
You're not the first to get hit with this bug on here
each browser has find on page functionality (ctrl+F). Is there a way to detect user searches in javascript so that I could attach additional actions.
Here is a solution which can account for alternative page find situations (ex. Command+F, '/' on Firefox). It checks for any of these keypresses and sets a timer when they occur. If the window is blurred soon after, then it is assumed that the Find dialog is showing.
Disadvantages: does not account for the "Find" dialog being launched via the menu. I don't see any way to be sure about this part, since (as far as I know, at least) browser UI is off-limits to Javascript running inside the DOM.
var keydown = null;
$(window).keydown(function(e) {
if ( ( e.keyCode == 70 && ( e.ctrlKey || e.metaKey ) ) ||
( e.keyCode == 191 ) ) {
keydown = new Date().getTime();
}
return true;
}).blur(function() {
if ( keydown !== null ) {
var delta = new Date().getTime() - keydown;
if ( delta >= 0 && delta < 1000 )
console.log('finding');
keydown = null;
}
});
jsFiddle, tested in Chrome, Safari and Firefox
You could do (to detect whenb a user press ctrl+f):
window.onkeydown = function(e){
if(e.keyCode == 70 && e.ctrlKey){
//user pressed ctrl+f
}
Fiddle here: http://jsfiddle.net/d8T72/
Of course you can try to hook into ctrl+f or cmd+f shortcut, but even if that works on "some" browsers, that way you only would know that an user pressed that shortcut and is most likely to search for something.
If the browser allows to overwrite that shortcut, you could further block the default behavior and implement your own search logic on the site. But that is considered most times as very bad practice. Overwritting native browser behavior is pretty pretty bad.
On the other hand, there is no "event" which gets triggered when a browser executed a search process. In short words, no, there actually is no way to detect or hook into a search process with javascript (if there is one, it's never gonna be cross browser compatible).
As initially suggested by #Nicola Peluchetti, here is a slightly improved version by feature sniffing:
window.onkeydown = function(e){
var ck = e.keyCode ? e.keyCode : e.which;
if(e.ctrlKey && ck == 70){
alert('Searching...');
}
}
Browser search test case »
As the default behavior of IE is to switch to the full screen mode on Alt-Enter command. I've to avoid this and have to attach a custom behavior.
Is it doable?
Not in JavaScript, no.
This is a behaviour of the application, which you don't really have control over (aside from browser extensions, and such).
You could try catching the key presses on your page, but it wouldn't prevent the user from easily circumventing it.
See http://www.webonweboff.com/tips/js/event_key_codes.aspx for a list of the character codes for keys. I'm pretty sure it's not reliable for catching combinations of key presses.
Besides, Alt+Enter in IE results in an expected behaviour and you should not try to override this via a webpage.
Since you can't beat 'em, join 'em. Meaning, since you can catch the event but can't stop it, how about you just run the same command in a timeout after the user presses alt+enter?
Example:
<script type="text/javascript">
document.onkeydown = handleHotKeys;
function handleHotKeys(e) {
var keynum = getKeyCode(e);
var e = e || window.event;
if (keynum==13 && e.altKey) { // handle enter+alt
setTimeout("toggleFullscreenMode",100);
}
}
function getKeyCode(e){
if (!e) { // IE
e=window.event;
return e.keyCode;
} else { // Netscape/Firefox/Opera
return e.which;
}
}
function toggleFullscreenMode() {
var obj = new ActiveXObject("Wscript.shell");
obj.SendKeys("{F11}");
}
</script>
DISCLAIMER: Tested in IE8. You will have to look at the browser and version to get this to work for the specific version of the browser you are targeting. This also assumes that the user will have javascript and activex objects enabled.