Search code examples
jqueryeventhandler

Passing custom data is different between focus and change event jQuery


I have a fiddle at https://jsfiddle.net/ws1hz5uf/ which demonstrates how to pass extra data to the target event.

The first button (Go 1) trigger focus on the text input

<div class="enclosing1">
<input type="text" id="example">
<label for="example">Test label 1</label>
<input type="button" id="test1" value="Go 1">
</div>

$(".enclosing1").on("click","#test1", function() {
    $("#example").trigger("focus", [true]);
});

$(".enclosing1").on("focus", "#example", function(event, isAutoTrigger) {
    console.log(isAutoTrigger);
});

The second button (Go 2) trigger change on the dropdown list.

<div class="enclosing2">
<select id="test-select">
  <option value="1">Option 1</option>
  <option value="2">Option 2</option>
  <option value="3">Option 3</option>
</select>
<label for="test-select">Test label 2</label>
<input type="button" id="test2" value="Go 2">
</div>
$(".enclosing2").on("click", "#test2", function() {
    $("#test-select").trigger("change",[true]);
});

$(".enclosing2").on("change", "#test-select", function(event, isAutoTrigger) {
  console.log(isAutoTrigger);
});

Looking at the console I can see clearly that focus' event handler can not receive the extra param from the trigger call while that of change can. Considering the consistency in the description of trigger and on methods of jQuery API, I don't understand why there is such discrepancy in how event handler treats extra data. Could anyone please shed some light for me?


Solution

  • I found the cause: focus is a special event of jQuery and its event handler does not accept extra parameter. Hence change the event from focus to focusin solve the problem.