0

Is it possible to run a JavaScript function only when the cursor focus is in a specific textarea?

I want to perform an action on keypress of the enter key, however I don't want this event listner to be in place just generally on the page, rather only when the cursor is in the textarea I have (id is postcontent)

As an example, the function I'm using is this:

function onEnter(){
   if(characterCode == 13)
   {
       console.log("Enter pressed");
   }
}

Just as a start while I work out the focus issue...

I also have jQuery at my disposal.

Francesca
  • 26,842
  • 28
  • 90
  • 153
  • possible duplicate of [How to detect pressing enter on keyboard using jquery?](http://stackoverflow.com/questions/979662/how-to-detect-pressing-enter-on-keyboard-using-jquery) – George Oct 17 '14 at 09:56
  • http://stackoverflow.com/questions/6178431/how-to-catch-enter-keypress-on-textarea-but-not-shiftenter – George Oct 17 '14 at 09:57
  • @George where does that question answer the issue of running only on focus of a specific text area? – Francesca Oct 17 '14 at 09:57
  • You would just [attach the event handler to your textarea](http://jsfiddle.net/647vzpzn/) rather than the document. I.E: `$('textarea').keypress(..)` rather than `$(document).keypress(..)`. – George Oct 17 '14 at 09:58
  • `$('#postcontent').on('keypress', onEnter)`. I would try `keyup` instead. – emerson.marini Oct 17 '14 at 09:59
  • And just so you know, you wouldn't be able to handle any `key` `event` in an element unless it's actually `focused`. So you can actually ignore the `focus` handling. – emerson.marini Oct 17 '14 at 10:21

2 Answers2

1
div1.onfocus=
function onEnter(){
       if(characterCode == 13)
       {
           console.log("Enter pressed");
       }
    }
Takpar
  • 29
  • 6
0

Here is an alternative:

var textArea = document.getElementById("postcontent");

textArea.addEventListener("keypress", handleKeyPress, false);

function handleKeyPress(e) {

    var characterCode = e.charCode;

    if (characterCode == 13) {
        console.log("Enter pressed");
    }

}

Fiddle

jyrkim
  • 2,849
  • 1
  • 24
  • 33
  • ups, I just realized that maybe I misunderstood the question, if it was meant that the event should be focus on text area. I guess user3764857 got it right – jyrkim Oct 17 '14 at 10:11
  • 1
    Nope. You wouldn't be able to handle any `key` `event` in an element unless it's actually `focused`. You're right. – emerson.marini Oct 17 '14 at 10:20