简体   繁体   中英

Javascript only when cursor focus within textbox

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM