Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Focus Which not triggered by click

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

$('#input').focus(function(){
  if(not come from click)
  {
    alert('Holla!');
  }
});
like image 982
Wildan Muhlis Avatar asked Jun 16 '13 06:06

Wildan Muhlis


2 Answers

To tell between "focus" events that come from keyboard and those that come from mouse, you can track the mouse events.

First, to understand the sequence of events that happen when you click an input, or Tab into it, look at the following jsfiddle: http://jsfiddle.net/orlenko/fyFkk/

In it, we'll log mousedown, mouseup, click, focus, and blur events.\

<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 simply click on the input, and then on another control, we'll get the following:

  • mousedown
  • focus
  • mouseup
  • click
  • blur

But if we tab into and out of the input, we'll see in the console:

  • focus
  • blur

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

$(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);
    });

});

A fiddle with this example: http://jsfiddle.net/orlenko/cwRAw/

like image 196
orlenko Avatar answered Sep 29 '22 15:09

orlenko


Use keyup

 $('#input').keyup(function(){
    alert('Called only when the focus is on element through keypress');
 });
like image 29
Chubby Boy Avatar answered Sep 29 '22 17:09

Chubby Boy