Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind multiple actions to a keyboard event [duplicate]

I am trying to make a chrome extension that modifies the text in an active text area of a Facebook chat window. But I want the change to take place only when the user presses the enter key so that the text doesn't change while it is still in the textarea. I want it to happen using javascript and make it feel like it's happening in the background although I want it to get triggered on the keydown event of the enter key.

Now the relevant JavaScript for the chat window's textarea in Facebook is:

<textarea class="blah" 
onkeydown="window.Bootloader && Bootloader.loadComponents(["control-textarea"], 
function() { TextAreaControl.getInstance(this) }.bind(this)); ">
</textarea>

And in my extension's JavaScript file. I bind the keydown event using something like this:

//elem is bound to the focussed textarea object
elem.onkeydown = function(evt) {
              if(evt.keyCode == 13){
                 //Some javascript code I want to execute here...
               }
        };  

I think as soon as the user presses the enter key, the textarea is cleared and some sort of a post request is made. So I lose the scope of the text I wanted to modify using JavaScript. I checked that the enter key binding is working for my extension by pressing shift + enter, and it modified the text without a problem. So my script is working fine.

However I want my script to be executed before the textarea is cleared and the post request is made. I just don't want the user to see the text getting modified.

Can I add/modify the keybinding of the textarea used by Facebook as shown above in my script for the google chrome extension? Any help is deeply appreciated.

like image 679
Annihilator8080 Avatar asked Nov 03 '22 21:11

Annihilator8080


1 Answers

There are a million duplicates of this question on here, but here goes again anyway:

You can use target.addEventListener(type, listener[, useCapture]); In your case, it would be

document.addEventListner(keypress, function(event) { //You can use keydown too
  if (event.which === 13) { // Value for Enter key if keydown or keyup used, use event.keyCode
    //some code that you want to add
  }
}  

If you are using jQuery, you can use

$(document).keypress(function(event){
 if (event.which === 13) { 
   // Your code here
 }
});

P.S. - In case of adding crossbrowser support, you should use something like this:-

if (target.addEventListener) {
  target.addEventListener('keypress',myFunction,false);
} 
else if(target.attachEvent) {
  target.attachEvent('onkeypress', myFunction, false);
} else {
  target.onkeypress = myFunction;
}
// Here myFunction is the callback where you would check for the character code and your custom code
like image 122
computnik Avatar answered Nov 11 '22 03:11

computnik