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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With