views:

443

answers:

1

I've got this Prototype code to detect Enter pressing in textarea.

document.observe('keydown', function(e, el) {
    if ((e.keyCode == 13) && (el = e.findElement('.chattext'))) {
        e.stop();
        // foo bar
    }
}

And html

<textarea id="chattext_17" class="chattext" cols="20" rows="3"></textarea>

But the problem is, that event gets invoked twice. I even tried to rewrite it to jQuery

$('.chattext').live('keydown', function(e) {
    if (e.keyCode == 13) {
        e.preventDefault();
        // foo bar
    }
});

But even then the event gets invoked twice.

When I try to debug it with FireBug, it always jumps here after completing the event handler

function createWrapper(element, eventName, handler) {
    var id = getEventID(element);
    var c = getWrappersForEventName(id, eventName);
    if (c.pluck("handler").include(handler)) return false;

    var wrapper = function(event) {
        if (!Event || !Event.extend ||  // always false here
            (event.eventName && event.eventName != eventName))
            return false;

        Event.extend(event);
        handler.call(element, event); // here the event gets called again
    };

    wrapper.handler = handler;
    c.push(wrapper);
    return wrapper;
}

I'm no Prototype guru, so I don't know where the problem could be.

Why is the keydown event invoked twice?

+1  A: 

Works for me. See for yourself at http://jsbin.com/ibozo/edit

<textarea id="chattext_17" class="chattext" cols="20" rows="3"></textarea>
<div id="dbg"></div>

script:

document.observe('keydown', function(e, el) {
    if ((e.keyCode == 13) && (el = e.findElement('.chattext'))) {
        e.stop();
        $('dbg').insert('<div>enter pressed</div>')
    }
})

Each debug statement gets inserted exactly once on each press of the [Enter] key. The jQuery version (not posted) behaves exactly the same.

You're doing something else wrong. Perhaps running the function that does the binding twice?

Crescent Fresh
wow lol, I found out that I had the js file linked twice ... anyway thx :)
Darth