Capture onkeydown event in Safari

Hi all…

Been at it for several hours now. Argh… Below javascript code works on IE7 and FF2, but not Safari. Anyone can decipher this and pinpoint a troublespot for Safari (as I don’t have a Mac here). My goal is to capture the enter key if the focus is within a certain div.


<div id="div1" onkeydown="return searchEnter(event)">
<input name="keyword1" type="text" value="Test data" id="keyword1" size="15" /><a id="aKeyword" href="add_data.html">&raquo;</a>
</div>


function searchEnter(e)
{ if (!e) e = window.event;
 key = e.keyCode ? e.keyCode : e.which;
 if (key == 13) {
   var button = document.getElementById('aKeyword');
   if (button.click) {
     button.click();
   } else {
     var qry =
document.getElementById('keyword1').value;
     self.location = 'add_data.html?q=' + qry;
   }
  return false;
  } else {
  return true;
  }
}

Cheers,
-rob

Hi Rob, Welcome to SPF!

I’m not sure, but try ‘onkeypress’ instead of ‘onkeydown’.

assign the keydown event to the input element,
divs don’t get focus, blur or key events in Safari.
That may change tomorrow…

keydown does not necessarily get to know what key was pressed. Its use should be limited to testing if any key was pressed. To test what key was pressed use the keypress event instead as that will always be passed the code of the key that was pressed.

Thanks for the welcome. This is a great forum.

onkeydown/onkeypress works and even within the div or at the input works (maybe for “yesterday’s” Safari?). I made an alert to see if it returns the item in the input text and it did so we know it’s not the event itself.

Now I believe the culprit may be the self.location. I tried window.parent.location.href, document.location.href.

Then I found a service at browsrcamp.com where I could test Safari, then some more js research and trial and error… BINGO!! the best redirect code: window.open(sUrl,‘_self’) did the trick for FF2 and Safari.

Problem solved, thread closed. :slight_smile:

keydown, keypress and keyup return different things in different browsers. I’m not sure about Safari, but it is based on Gecko…

IE returns a property called keyCode for all three, but the actual character code (for ‘Q’ instead of ‘q’ when you press ‘shift’) is returned only on the keypress event.

firefox returns a keyCode for down and up, but you have to ask for
a charCode for a key press event.

However, firefox returns a character code (of ‘0’) AND a keyCode on keypress when you press a function key.

Opera seems to use the IE model, keyCodes for all events, the character code returned on press.

In practice on keypress you can return the event.charCode (if there is one and it’s not 0) or else return the event.keyCode;

For keyup and keydown you get consistent results from keyCode.