Search code examples
javascriptjqueryjquery-eventsevent-bubbling

preventDefault() for keypress cancels change event


In the code snippet below, I'm trying to prevent the user from entering new lines into a <textarea> by using preventDefault(). Instead of entering new lines, I want the enter key to trigger the blur event. However, the code below is bypassing the change event after the user changes the text within the <textarea> and then hits enter. How can I ensure that the change event always fires when the value of the text is changed?

$('textarea')
.keypress(function (event) {
    if (event.which == '13') {//13 = Enter
        event.preventDefault();
        $(this).blur();
    }
})
.change(function() {// THIS DOES NOT FIRE IF USER PRESSES ENTER
    alert('change event');
})
.blur(function() {
    console.log('blur event');
});//end: blur()

Solution

  • Looks like it is a problem with the event ordering. In IE change event is fired first then blur event is fired but in Firefox and Chrome it is the opposite. So when you fire blur() event manually in Firefox and Chrome it causes the focus event to fire, but in IE it won't.