0

I can't seem to figure out why the toggle doesn't work after my ajax xml load. It pulls the xml correctly. However, fails to execute the toggle.

Here is the jQuery onclick both xml load and toggle

      $("document").ready(function(){

           $("#demo").on("click", loadxml);
           $("#demo-2").click(function(){
              $("li").toggle("fast");        
          });
        });

The loadxml function :

    function loadxml(){
     var xhttp = new XMLHttpRequest();
     xhttp.onreadystatechange = function(){
         if (xhttp.readyState == 4 && xhttp.status == 200) {
             myFunction (xhttp);
          }
    };
    xhttp.open("GET","xml/categories.xml", true);
    xhttp.send();
}

 function myFunction(xml){
      var i;
      var xmlDoc = xml.responseXML;
      var list = '<ul id="demo-2" class="list-unstyled no-bullet"><span class="glyphicon glyphicon-folder-open" aria-hidden="true"></span> Categories';
     var x = xmlDoc.getElementsByTagName("Categories");

  for(i=0; i<x.length; i++) {
        list += '<li><span class="glyphicon glyphicon-minus" aria-hidden="true"></span>' +  x[i].getElementsByTagName("CategoryName")[0].childNodes[0].nodeValue + "</li>";
}

list += "</ul>"

document.getElementById("change").innerHTML = list;

}

Here is the html:

        <div class="container" id="change">
             <ul id="demo"></ul>
         </div>
MPO
  • 1
  • 1

2 Answers2

1

This code:

$("#demo-2").click(function(){
   $("li").toggle("fast");        
});

Should be:

$("#change").on('click','#demo-2',function(){
   $("li").toggle("fast");        
});

Thats because your are adding dinamic content on your #change selector.

Hackerman
  • 12,139
  • 2
  • 34
  • 45
0

I'm pretty sure it's not working because of when you are binding the click event.

If you're sending the xmlhttp request after your document ready event is fired, you've already bound the click event to '#demo-2', which is not there yet. Im pretty sure you need to defer the binding until after you insert the element into the dom.

No problem. If Hackerman's solution works, it's more elegant, and honestly, correct, than what I was thinking. But, if not: I was thinking that you should wait to bind until after

document.getElementById("change").innerHTML = list;

That way the content is loaded into the dom, and then the click event is bound.

// Just for simplicity, I'm pretending your xml is returned from the function
var xml = loadxml();
myFunction(xml);
// Now, bind your click event to the new element
Mike
  • 1
  • 1