Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 849
bento Avatar asked Oct 25 '12 22:10

bento


2 Answers

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);
like image 162
Nelson Avatar answered Sep 27 '22 21:09

Nelson


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

like image 35
Reflective Avatar answered Sep 27 '22 20:09

Reflective