In my latest code, I have an event handler for a focus
on a textarea. When the user clicks on the textarea, that event-handler is triggered which sets some other DOM states based on the selected textarea. However, elsewhere in my program I want to programmatically set the focus
of the textarea without triggering that event handler. I know Backbone, for instance, has a way to silently
perform an action.
My only pseudo-solution is to temporarily set a variable:
var silence = true;
And then, in my event handler, only perform the logic if silence is false. The handler is still triggered, but the logic doesn't run.
Does anyone else know of better strategies for this?
You could temporarily unbind()
the event, like this:
You have the following scenario where you handle the focus event:
function focus_handler() {
//focus handler code
...
...
}
$('#yourelement').bind('focus', focus_handler);
And now on the part of the code where you want to programmatically focus the element without triggering the event handler:
$('#yourelement').unbind('focus');
$('#yourelement').focus();
$('#yourelement').bind('focus', focus_handler);
<input type="text" name="input" id="input" value="0">
<input type="text" name="input" id="input2" value="0">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js" type="text/javascript"></script>
<script>
$(function() {
$('#input').focus(function(a,b) {
if (b) alert('forced');
});
$('#input').trigger('focus', jQuery.Event("focus"));
});
</script>
When b
argument of the event handler is present, the event is triggered by invoking $('#input').trigger('focus', jQuery.Event("focus"));
. So you can make you handler function execute depending on normal focus or forced focus.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With