content top

How to override jQuery Event Handlers

An interesting problem that I came across today was figuring out how I could elegantly externatize my jQuery functions and bind or unbind them to particular events in a way that would override previous event handling attachments if necessary. The way to go about achieving this is to first define your function as the product of a new variable. 

var myAction = function() { alert(‘Lights, Camera, Action!’) ;

Now that this has been defined, the next part of our procedure is attaching the function to an Object’s event so that it can be triggered when a user does something (eg. a click or mouseover event) – in this post, I’ll be using a div called myButton as an example. BelowI have assigned the action myAction to this button. When a user clicks it they will see an alert – simple enough.  

Next, a scenario may arise where you would wish to unassign the event you just delegated to myButton – For example: Click was previously told to exectue one specific function but the user-case requires the same button to do something else now that they’ve played around with your page. In order to faciltate this behaviour we first use unbind to remove the first action that was assigned to the button. When you click it it now doesn’t do anything. At this point if I wanted to I could easily define a new function that can be assigned to myButton OR just rebind the old event to the same Object.

 

//Define a second action
var myAction2 = function() { alert('I'll set Christian Bale on you!')};

//Attach your first action to a click event
$
('#myButton').click(myAction);

//Unbind the action from your Objects click event
$('#myButton').unbind('click', myAction);

//Adjust it back to that it works again
$
('#myButton').click(myAction);

// Turn it off once more
$('#myButton').unbind('click', myAction);
 

//Assign the second event to it
$
('#myButton').click(myAction2);

 

 

And thats it. Let me know if it comes in useful ;)

Bookmark and Share
Share

Related posts:

  1. jQuery Colour Selector plug-in with support for graceful degradation Hey guys. Here’s another entry on jQuery that someone...
  2. How to highlight terms on your page using jQuery Today I came across a really useful plugin for jQuery...
  3. How to enlarge images with jQuery Guest writer,  Jeffrey Jordan Way. I’ve created many tutorials...
  4. 7 Really Useful Tips For Better jQuery Code   I’ve been using jQuery in my web apps for...
  5. jQuery UI Animation Effects The jQuery UI Effects Core brings a few more...

Related posts brought to you by Yet Another Related Posts Plugin.

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment