I have a contenteditable div and when you type in it, after 2 seconds I try to change its background color.
This is my code:
function changeFn(){
$(this).css('background','red')
console.log($(this).attr('id'));
}
var timer;
$("div.content").on("keypress paste", function () {
clearTimeout(timer);
timer = setTimeout(changeFn, 2000)
});
It seems that I have to pass $(this) to the function because it doesn’t recognize which $this is.
When I set the background-color change inside the keypress function it works.
jsFiddle: http://jsfiddle.net/uc8Tg/
Use
jQuery.proxy, which sets the context of a function:Example: http://jsfiddle.net/uc8Tg/1/