Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS: How to detect whether cursor is in textfield

I want to use some letters ( keys ) as shortcut for some actions in javascript. I want to check whether the cursor is focused on any textfield, form input, etc. so that the shortcut action will be canceled when user is typing something in a form or textfield.

For example, i want an alert() to be executed when user presses 'A'. But if the user is typing some text in a textarea like 'A website' then he will be pressing 'A', this time alert() should not be executed.

like image 669
Prakash GPz Avatar asked Mar 26 '13 12:03

Prakash GPz


People also ask

How to find the cursor position in JavaScript?

Using event. It is used to find out the position of the cursor in the vertical direction or on the Y-axis where the event was triggered. Similar to the event. clientX property, it also returns a numeric value that holds the position of the cursor on the Y-axis or Y-coordinate.

How do I find my cursor position?

In Mouse Properties, on the Pointer Options tab, at the bottom, select Show location of pointer when I press the CTRL key, and then select OK. To see it in action, press CTRL.

How do you know if input field is focused?

css("visibility"); var chattitle = $("#hideid"). text(); if (chatattr == "visible") { if (MY INPUT FIELD HAS FOCUS) { $.

How do you get a caret position in input?

You also need the input's selectionDirection to get the caret position whenever selectionDirection is backward i.e. you make a selection left-ward in the textbox so that selectionStart is the caret, but when selectionDirection is forward the caret will be at selectionEnd. @oldboy yes that would work.


2 Answers

$(document).keydown( function( e ) { 
  if( e.target.nodeName == "INPUT" || e.target.nodeName == "TEXTAREA" ) return;
  if( e.target.isContentEditable ) return;

  // Do stuff 
}
like image 134
Thomas C. Rodriguez Avatar answered Oct 09 '22 23:10

Thomas C. Rodriguez


window.onkeydown = function(e){
  if ( e.target.nodeName == 'INPUT' ) return;

  handle_shortcut();
};
like image 30
Jeffrey Avatar answered Oct 09 '22 23:10

Jeffrey