OnKeyUp without jQuery?

I am trying to capture onKeyUp when a keystroke is entered without using jQuery.

My current code is:

$('#chatboxtextarea').on('keyup', function (e) {
        var msg = document.getElementById('chatboxtextarea').value;
        if (msg.replace(/\r/g, '\\\\r').replace(/\n/g, '') != "" && e.keyCode == 13) {
            var textarea = document.getElementById('chatboxtextarea');
            textarea.value = '';

            .....code to send.....


        } else if (msg.replace(/\r/g, '\\\\r').replace(/\n/g, '') == '') {
            var textarea = document.getElementById('chatboxtextarea');
            textarea.value = '';
        }
    });

How can this be done instead of regular JavaScript?

+5
source share
2 answers

Simply:

document.getElementById('chatboxtextarea').onkeyup = function (e) {
    e = e || window.event;
    var textarea = this;
    var msg = textarea.value;
    if (msg.replace(/\r/g, '\\\\r').replace(/\n/g, '') != "" && e.keyCode == 13) {
        textarea.value = '';

        .....code to send.....

    } else if (msg.replace(/\r/g, '\\\\r').replace(/\n/g, '') == '') {
        textarea.value = '';
    }
};

change

Alternatively, you can call something like the following to add an event; passing an element object, an event type (without 'on'), a call function, and using capture to use various browser methods:

function addEvent(elm, evType, fn, useCapture) {
  if (elm.addEventListener) {
    elm.addEventListener(evType, fn, useCapture);
  }
  else if (elm.attachEvent) {
    elm.attachEvent('on' + evType, fn);
  }
  else {
    elm['on' + evType] = fn;
  }
};

t

addEvent(document.getElementById('chatboxtextarea'), 'keyup', 
  function(e) {
    e = e || window.event;
    ...
  }, false);
+3
source

jQuery does a lot of complex code inside, which would be hard to just mimic. If you want to associate the same event with the specified ID, this is not so bad.

To select an item:

document.getElementById('chatboxtextarea')
document.querySelector('#chatboxtextarea')
document.querySelectorAll('#chatboxtextarea')[0]

To attach an event:

.addEventListener('keyup', function (e) {

IE8- .attachEvent, . .onkeyup.

0

All Articles