bento bento - 1 month ago 9
Javascript Question

performing a javascript event without triggering that event handler

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?

Answer
<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.