22

I have these functions:

TargetWorksheet.toggle_child_locations = function(id){
  $("#location-children-"+id).slideToggle("slow"); 
}

TargetWorksheet.get_child_locations = function(id, lvl){
  //Ajax grab all children and targets, and display children
  $.get('child_locations',{ location_id: id, level: lvl}, function(data){
    $("#location-children-"+id).append(data);
    TargetWorksheet.toggle_child_locations(id);
  });

  //Change onClick to just toggle since child data will now be loaded
  $("#location-toggle-"+id).click(function(){
    TargetWorksheet.toggle_child_locations(id);
  });
}

and this call:

$(function(){
  TargetWorksheet.toggle_child_locations(2);
  $("#location-toggle-2").click(function(){
    TargetWorksheet.get_child_locations(2,1);
  });
});

So I attach a click event to my '+' link (#location-toggle-2), which toggles child data. On first click, I want to do an ajax call to retrieve the child data, but then i just want to overwrite the .click on the #location-toggle-2 so that it now just toggles, and doesn't make the ajax call. The above code doesn't work, it doesn't seem to overwrite the .click, and makes the ajax call each time.

Does anyone know how I can overwrite the .click event of an item? I also tried $("#location-toggle-"+id).click(TargetWorksheet.toggle_child_locations(id)); And it just kept toggling over and over recursively for some reason.

Thoughts?

1 Answer 1

67

The only thing you're missing there is that using .click() adds a new handler every time it's called, not overwrites an existing one.

You can use $("#location-toggle-"+id).unbind() to clear handlers on that element before adding the new one, and it should work as you expect.

Sign up to request clarification or add additional context in comments.

2 Comments

It would be better to use unbind("click");, this will unbind the click event type only. This is particularly useful when using JQueryUI widgets like button(), in this case you just want to unbind the click and keep other events like hover and so on..
Don't forget about chaining. I usually do this: $("#myElement").off("click").on("click", handler); This makes the code a bit cleaner

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.