Function doesn't work after jQuery ajax html injection

I have the following ajax call on a webpage...

    var href=$('.poplight').attr("href");
    $('.poplight').attr("href","#");
    $('.poplight').click(function(){
        $.get(href, function(data) {
                $("#popup-contents").html(data) 
                    // inserts <div id="additionalInfo"> 
                    // <legend id="legend-params">Legend</legend>
                    // <div id="toggle"> This should toggle </div> </div>

            }
        );
    });

</script>

On the same page, there is a .js script linked that toggles the #toggle div whenever the legend is clicked. This all works fine on a separate page (just the legend toggle by itself), but I can't get it to work with the ajax call. I'm thinking it has to do with when jquery "attaches" to certain doms... I don't know enough about the innerworkings of jquery to really know for sure.

Here is the external script. I've tried with an onload, adding it inline with html, and a few other variations. These functions are run when the legend is clicked (if you insert an alert('test') after the .show() method, it will display an alert window).

$('#toggle').hide();                                            
$("#legend").toggle(
    function() {
       $("#toggle").show("slide", {direction: "up"}, 200);
    }, 
    function() {
       $("#toggle").hide("slide", {direction: "up"}, 200);
});

Any help would be great!

Answers


The comments listed above helped me solve the problem (I think they were converted to comments by SO's "algorithm"... would have marked them as answers). I essentially changed:

$("#legend").toggle(...) to

$("#legend").on('click', functionX()...) where functionX that was pretty much a glorified if statement that hid some things if a global variable was true or false. Maybe not the cleanest solution, but it did the job.


Need Your Help

What is Repo and Why does Google use it?

android git repository

When I wanted to get Android source code, I knew that I have to use "repo". So what is repo? Why do they use repo and not just use GIT?, and is there a GUI for repo that enables me to pause/resume

Present period in a string without negative numbers

java jodatime

in a joda-time based project I am trying to present the user with the period between 2 dates in a readable format.