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

Best place to Sort a List of Tasks

oop data-structures sorting collections

Im building a web application which is a process management app. Several different employee types will be shown a list of Tasks to do and as each one completes a task then it is moved on to the next

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.