Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onKeyUp without jQuery?

I am trying to capture onKeyUp when enter is pressed without the use of 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 could this be done in regular JavaScript instead?

like image 314
Alosyius Avatar asked Oct 22 '22 15:10

Alosyius


1 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 = '';
    }
};

edit:

Alternatively you could call something like the following to add the event; passing the element object, the event type (without 'on'), the function to call and whether to use capturing, just to utilise the different 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;
  }
};

ie:

addEvent(document.getElementById('chatboxtextarea'), 'keyup', 
  function(e) {
    e = e || window.event;
    ...
  }, false);
like image 60
C.. Avatar answered Oct 24 '22 09:10

C..