Reputation: 113
I'm fairly new to web development and I'd like to think I am getting the hang of it, the only major problems I keep running into are cross-browser compatibility issues.
I have a textarea on a webpage that will call a function after the user is done typing. In order to do this, I am using jQuery and setTimeout to wait a bit before calling the function. This ensures that the function isn't called after every single keypress. I don't want it called after every keypress because the function sends a request to a servlet which does some processing and returns.
The code works fine on Chrome (I use Chrome for debugging it), but it doesn't work with IE7. Here it is:
var timer = null;
$("#scriptInput").keypress(function() {
clearTimeout(timer);
var thisEvent = window.event;
timer = setTimeout(function() {validateScript(thisEvent);}, 500);
});
function validateScript(evt) {
var code = (evt.keyCode) ? evt.keyCode : evt.which;
//check which key was pressed...
//don't need to send a request on key presses of CAPSLOCK, SHIFT, and ARROW keys
if(code != 20 && code != 16 && code != 37 && code != 38 && code != 39 && code !=40){
sendRequest(2);
}
}
As you can see, I've already made numerous attempts at implementing compatibility with IE7, but to no avail :\
It must be compatible with at least IE7 because it will be used by a number of machines which use IE7 and don't have the privileges to upgrade.
Let me know if you need anymore info! Thanks!
P.S. "scriptInput" is the id of the textarea this is affecting.
Upvotes: 0
Views: 93
Reputation: 318578
var thisEvent = window.event;
is not cross-browser compatible - not all browsers use the global event
object but a function argument instead.
jQuery always provides you with an event object as a function argument, so simply remove the above assignment and change your code like this:
$("#scriptInput").keypress(function(thisEvent) {
...
});
jQuery also normalizes the various properties for the pressed keys into e.which
so you can get rid of var code = (evt.keyCode) ? evt.keyCode : evt.which;
and simply use evt.which
all the time.
You can also improve/shorten the whole thing a bit more. If adding another library is fine I'd use _.debounce
from Underscore.js to do the timing:
$("#scriptInput").keypress(_.debounce(validateScript, 500));
Instead of Underscore.js you could also use a jQuery plugin providing that functionality.
If adding additional third-party code is not an option I'd store the timer on the element instead of a (possibly global) variable:
$("#scriptInput").keypress(function(e) {
var $this = $(this);
window.clearTimeout($this.data('timer'));
$this.data('timer', window.setTimeout(function() {
validateScript(e)
}, 500));
});
Upvotes: 3