Search code examples
internet-explorerprototypejsdom-events

Preventing bell/ding in a PrototypeJS event handler


How do I translate the following to instead use PrototypeJS Event.observe?

<input type="text" .... onkeypress="if(event.keyCode==13)return false;">

The purpose being to prevent the ding which in some cases should not play (in IE9).


Solution

  • What you've quoted would look like this using Prototype's event stuff:

    var input = /* ...get the `input` element, how will depend on your structure... */;
    input.observe('keypress', function(event) {
        if (event.keyCode == 13) {
            event.stop();
        }
    });
    

    Event#stop does two things: It prevents the default action, if any, and it stops the event bubbling. If you just want to prevent the default action but not bubbling, use Event#preventDefault instead (Prototype will make sure it's there, even on browsers that leave it off); if you just want to stop bubbling but not prevent the default action, use Event#stopPropagation instead (again, Prototype will make sure it's there).


    In terms of finding the input element: If it has an id, that's easy:

    var input = $('theId');
    

    Alternately, you can find it by where it is, or by its other attributes, using $$, which offers fairly powerful selectors (most of CSS3).