开发者

How to attach behaviour to a document

开发者 https://www.devze.com 2023-03-19 15:34 出处:网络
I am trying to bind the KeyDown event to all "Input type=text" controls in the document. I can\'t rely on CSS selectors because the page change dynamically, so I only know that when

I am trying to bind the KeyDown event to all "Input type=text" controls in the document. I can't rely on CSS selectors because the page change dynamically, so I only know that when there is an "Input type=text" in the page, I must catch the keydown event and do something with it..开发者_开发问答..

I heard about document.addEventListener() but I am not sure if this is the good approach and how to use it.

I am newbie with Javascript and DOM, help please.


ok guys, I found by myself the answer so I will share it.

my objective is catch all keydown events so I use addEventListener with the 3 parameters you can see below, first: event type name, second:function event handler,third: boolean Required that specifies whether the event needs to be captured or not.

window.onload = function () {

if (document.addEventListener)
{

//attach the event listener which acts globally to the document:
document.addEventListener("keydown",justDoIt,true);

}

}

function justDoIt(){ alert("hobbes");}

Finally, one more thing is missing, I dont know how to detect the id of the element where the event was triggered....if someone knows please reply.

That's all :P BTW just tested on Safari.¡ but it would work over IE and FireFox....

0

精彩评论

暂无评论...
验证码 换一张
取 消