Focus that is not triggered by a click

How to trigger an action when focusing input, but the focus event does not come from a click?

$('#input').focus(function(){ if(not come from click) { alert('Holla!'); } }); 
+6
source share
3 answers

To talk about the “focus” events that come from the keyboard and those that come from the mouse, you can track mouse events.

Firstly, to understand the sequence of events that occur when you click on a tab or tab in it, look at the following jsfiddle: http://jsfiddle.net/orlenko/fyFkk/

In it, we will register the events mousedown, mouseup, click, focus and blur. \

 <input type="text" id="zero"/> <input type="text" id="one"/> 

JavaScript:

 $(function() { var one = $('#one'); one.mousedown(function() { console.log('mousedown'); }); one.mouseup(function() { console.log('mouseup'); }); one.click(function() { console.log('click'); }); one.focus(function() { console.log('focus'); }); one.blur(function() { console.log('blur'); }); }); 

If we just click on the input and then on another control, we get the following:

  • mousedown
  • focus
  • mouseup
  • click
  • Blur

But if we enter outside the input, we will see in the console:

  • focus
  • Blur

So, if we keep track of the mousedown and blur events, we can tell between the keyboard-based focus and the mouse. For instance:

 $(function() { var one = $('#one'); one.mousedown(function() { console.log('mousedown'); $(this).data('mousedown', true); }); one.mouseup(function() { console.log('mouseup'); }); one.click(function() { console.log('click'); }); one.focus(function() { if ($(this).data('mousedown')) { console.log('You clicked it!'); } else { console.log('You tabbed it!'); } }); one.blur(function() { console.log('blur'); $(this).data('mousedown', false); }); }); 

Script with this example: http://jsfiddle.net/orlenko/cwRAw/

+5
source

Use keyup

  $('#input').keyup(function(){ alert('Called only when the focus is on element through keypress'); }); 
+1
source
 function ren(){ alert('Holla!'); } $('input').focus(ren); $('input').mousedown(function(){ $('input').off('focus',ren); }); $('input').mouseup(function(){ $('input').on('focus',ren); }); 

Do not check the focus function; instead, remove the focus function when pressed

Demonstration

+1
source

Source: https://habr.com/ru/post/947393/


All Articles