Thursday, June 19, 2014

Javascript - Dynamically Updating a Handler

One of the coolest, yet lesser promoted objects in the JavaScript world is the ability to dynamically update the handler of a given function. To break it down, a user essentially "re-programs" on the client side an interactive Html element (<a>, <div>, <span>, etc.) to change which function is called, when an option is selected (By whatever input method is used). This can save a ton of coding and can allow functions to change based on user entered parameters. It's feasible that the chosen value could be bound to a cookie, but otherwise the function will always load with the starting option selected by the developer. This may seem basic, but it's also incredibly powerful and useful in many scenarios. I used it to create mapping assistance, in which the destination (Which has to be concatenated with differing circumstances, based on user input) would be new per visitor and the destination may be different as well, based on where the visitor is travelling to. It creates an elegant, scale-able solution that can be easily updated with minimal code. 

THE SCRIPT (Within the Html header):

<script type="text/javascript">
function startHere(userChoice)
{
   if(userChoice=="iChooseThis")
   {
   document.getElementById(userChoice).onclick=nowDoThisFunction;
   }
   else
   {
   document.getElementById(userChoice).onclick=nowDoThisFunction2;
}

function nowDoThisFunction()
{
//Do this code;
}

function nowDoThisFunction2()
{
//Do this code instead;
}
</script>


HTML (Using the very crude example of acting based on the element clicked - you could change the function parameter to grab a text box value, drop-down menu, etc.):

<a id="iChooseThis" href="javascript:" onclick="javascript: startHere(this.id);" />

No comments:

Post a Comment