2

I have an anchor that when clicked makes an ajax call to load some html into a div and then load a script. I want to unbind that event after the first click, and replace it with another click event that toggles between showing and hiding that div. I've got this far, but none of my attempts to register the click event that toggles the div work.

$('#anchor').click( function() {
    $('#div').load('file.html', function() {    
        $.getScript('script.js');       
        $('#anchor').unbind();
    });
});
user883036
  • 113
  • 1
  • 1
  • 6

2 Answers2

2
$('#anchor').click( function(e) {
    e.preventDefault(); // prevent the browsers following the link
    $('#div').load('file.html', function() {    

        // make sure to bind once the new script has been included
        // i.e. within .getScript's callback
        $.getScript('script.js', function() {
            $('#anchor').unbind("click").click(myShowHideFunc);
        });       
    });
});
karim79
  • 339,989
  • 67
  • 413
  • 406
1

Try this with event namespace which help to unbind only the current event handler so that other click handlers are not touched when we unbind.

$('#anchor').click('click.anchor', function() {

    $('#div').load('file.html', function() {    
        $.getScript('script.js', function(){       
          $('#anchor').unbind('click.anchor').click(function(){
             $('#div').toggle();
          });
        });
    });
});
ShankarSangoli
  • 69,612
  • 13
  • 93
  • 124
  • 2
    I like the `one` handler, but in this case I would say it could lead to problems - e.g. the request fails, forcing the user to reload the page since the link cannot be clicked again. – karim79 Aug 07 '11 at 19:18