Reputation: 1654
I found that prototype.js library provides Event handling mechanism, but I can't figure out what's wrong with the following code snippet:
<div>
<div id="foo">Bla-bla</div>
</div>
<script type="text/javascript">
function onFooKeyup(e)
{
var element = e.element();
if (e.keyCode == Event.KEY_ESC)
element.innerHTML="TEST";
}
//document.observe('keydown', onFooKeyup);
$('foo').observe('keydown', onFooKeyup);
</script>
Basically I want to change content (or do styling, etc.) of certain div block when user press escape button. The problem is that observing the foo
id doesn't lead to any action, while observing the document (commented line) indeed trigger the change. If I replace my foo
div block with input tag, e.g.
<div><input type="text" id="foo" /></div>
then the events will be triggered correctly. Is it a bug?
Upvotes: 1
Views: 482
Reputation: 1
Man, I think the only error is because you are saying to jQuery to look for a tag named 'foo', and then bind the 'keypress' event to it. If you want it to search for your id 'foo' you should do the following
$('#foo').observe ....
Upvotes: 0
Reputation: 5693
This is because the event has not originated inside the <div>
element, so you can't observe
it (listen to it) there. In the case of the <div>
block with an <input>
tag, the event is actually originated inside that element (if the input has user focus, I think, but it's not relevant here). So no, it's not a bug.
Just catch the keyboard event at document level, because the key events will originate on different elements (different browsers manage this on different ways) but they will all bubble up to the document (unless you stop the event's propagation).
Upvotes: 1