views:

1932

answers:

1

I am trying to assign the onclick event to an anchor tag that already exists when I click on another element. However, everything I've tried seems to result in the firing of the event immediately after assignment. We're using Prototype and Scriptaculous.

This is the function:

<script type="text/javascript">  
 function loadData(step, dao_id) {
  var div_id = 'div_' + step;
  var anchor_id = 'step_anchor_' + step;
  var prv = step -1;

  switch(step) {
   case 1:
    var action = 'major_list';
    break;
   case 2:
    var action = 'alumni_list';
    break;
   case 3:
    var action = 'alumnus_display';
    break;
  }

  new Ajax.Request('awizard.php', {
    method: 'get',
    parameters: {action : action, dao_id : dao_id},
    onSuccess: function(data) {
     $(div_id).innerHTML = data.responseText;
     //$(anchor_id).observe('click', loadData(prv, dao_id, true));
     //Event.observe(anchor_id, 'click', alert('I executed'));

     showStep(step);

     //$(anchor_id).onclick = loadData(prv, dao_id, true);
     //$(anchor_id).observe('click', loadData(prv, dao_id, true));

    }
   }
  )     
 }

 function showStep(step, toggleBack) {

  var div_id = 'div_' + step;
  if(!toggleBack) {
   if(step != 1) {
    var prv = step -1;
    Effect.SlideUp('div_' + prv, { duration:1, delay:0 });
   }

   Effect.SlideDown(div_id, { duration:1, delay:1 });
   Effect.Appear('step_anchor_' + step, { duration:1, delay:2 });
  } else {

   var prv = step -1;
   Effect.SlideDown('div_' + prv, { duration:1, delay:0 });
   Effect.SlideUp(div_id, { duration:1, delay:1 });
   Effect.Fade('step_anchor_' + step, { duration:1, delay:2 });
  }    
 }
</script>

As you can tell I've tried multiple ways of assigning the onclick event to the anchor tag and none of them work properly. At first I assumed that the Effect.Appear function on the anchor tag could be firing the onclick event, so I tried moving the event assignment to after the showStep function but that didn't make any difference. Additionally, I tried calling the stop() function immediately after assignment but that didn't make any difference either.

I'm at my wits end with this. Is there any way for me to assign the onclick event to the anchor tag without having the event fire automatically? What am I doing wrong?

+3  A: 

Functions are first class object in Javascript, this means you can assign them to variables or pass them as arguments to other functions. In your code, you're confusing function calls with references to functions.

Take a look at this code:

$(anchor_id).observe('click', loadData(prv, dao_id, true));

What this does it pass the result of the call to "loadData" to the observe function. What you want to do is pass a reference to the function call instead. You can fix it easily by changing the code to this:

$(anchor_id).observe('click', function() { loadData(prv, dao_id, true) } );
Alexander Malfait