1

How can I check whether my_func was called from blur or focus, in the following code?

function my_func(my_arg) {
    // Maintain compatibility with ECMAScript < 6
    // https://stackoverflow.com/a/894877/1563422
    my_arg = typeof my_arg !== 'undefined' ? my_arg : false;

    if(my_arg) {
        // do something
    }
}

// Apply to both blur and focus, in case a user clicks from a field
// onto the background of the page, without focusing another field first
$('#appform').on({
    'blur' : my_func,
    'focus': my_func
}, 'input, select');
Danny Beckett
  • 20,529
  • 24
  • 107
  • 134

2 Answers2

3

The event object's type field will contain a name for the event that triggered it (though not always the same one you defined for the handler; blur becomes focusout for example):

The Event.type read-only property returns a string containing the event's type. It is set when the event is constructed and is the name commonly used to refer to the specific event, such as click, load, or error

https://developer.mozilla.org/en-US/docs/Web/API/Event/type

function my_func(my_arg) {
  console.log(my_arg.type);
}

$('#appform').on({
    'blur' : my_func,
    'focus': my_func
}, 'input, select');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="appform">
<input>
<input>
<select><option>a</option><option>b</option></select>
Daniel Beck
  • 20,653
  • 5
  • 38
  • 53
1

You might be able to get away with passing a bound function as the event handler.

$('#appform').on({
    'blur' : invalid_style.bind(null, 'from-blur'),
    'focus': invalid_style.bind(null, 'from-focus')
}, 'input, select');

The bind call returns a function object with some parameters already "bound" to it. In my example, we are passing a null as the context and then a string as the first argument to the invalid_style function.

Within your function, you will now be able to inspect the my_arg argument and decipher from where your function was called.


Reference: Function.prototype.bind()

Lix
  • 47,311
  • 12
  • 103
  • 131