If I have an event listener that listens for multiple events, is it possible to make it only trigger once per user action, even though the single user action spawns multiple events? Alternatively is there a way to determine if that handler has already been fired for the user action?
For example, in this jsfiddle (snippet below) the handler is called once each time I type in the text box (input
) and once when I leave the text box (change
).
When I click the checkbox, however, it is called twice (once for input
and once for change
). Although there are various ways I can mitigate this (for example by seeing what type of input the event came from and if it's a checkbox ignoring the 'input' event EDIT: or by changing the handler to only listen for the input
event, which would mean the handler is called only once for this specific example, but doesn't answer my question), I'm wondering if there is a built in way to prevent multiple calls to the handler when it comes from a single user action.
$('input').on('input change', function(e) {
$('#events').append('triggered by '+$(e.target).attr('id')+'<br>');
});
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<div>
Text input: <input type="text" id="text-input">
</div>
<div>
Checkbox: <input type="checkbox" id="checkbox-input">
</div>
<div>
<input type="button" value="Clear" onclick="$('#events').html('');">
</div>
<div id="events">
</div>
'); }); ``` – Biki Maharjan Mar 20 '21 at 19:40