I have this javascript function, which acts like a keyup but waits for the user to stop typing:
function afterDelayedKeyup(elements, action, delay){
if(typeof(elements) == "string"){
elements = $(elements);
}
elements.keyup(function(){
if(typeof(window['inputTimeout']) != "undefined"){
clearTimeout(inputTimeout);
}
inputTimeout = setTimeout(action, delay);
});
}
I call it like this:
afterDelayedKeyup(".foo", function(){ doSomething();}, 1000);
It works: if you start typing in a .foo input, then when you've not typed anything for 1 second, doSomething() is called.
What i want to do next, is to pass through the element it was called on into the doSomething() function, so doSomething knows which element triggered it to be called. I've tried this:
afterDelayedKeyup(".foo", function(){ doSomething(this);}, 1000);
and
afterDelayedKeyup(".foo", function(){ doSomething($(this));}, 1000);
But it doesn't seem to work. If my doSomething() function looks like this for example:
function doSomething(element){
console.log("element.attr('class') = "+element.attr('class'));
console.log("$(element).attr('class') = "+$(element).attr('class'));
}
Neither of them will log out 'foo' like i'd expect. I get either TypeError: undefined is not a function
(for the first log line) or $(element).attr('class') = undefined
for the second log line.
I think that the value of 'this' is getting lost somewhere in between being passed through to afterDelayedKeyup() and being passed through to setTimeout() but i can't work out what's happened.