Search code examples
javascripthtmldomxmlhttprequestdropdown

HTML added from another HTML file using JS displays correctly, but JS functions do not work


I would like an element of my html page to be taken from another html file. So, such a widget displayed on many pages at once.

I was able to write JS code so that the content of the element is taken from another file. Code below:

//* Accordion - replace */
var fn = (event) => {
  var xhr = new XMLHttpRequest();
  xhr.open("GET", '/widgets/accordion.html', true);
  xhr.onload = function (e) {  
    if (xhr.readyState === 4) {
      if (xhr.status === 200) {
        console.log(xhr.responseText)
        document.getElementById("accordion").innerHTML = xhr.responseText;
      } 
      else {
        console.error(xhr.statusText);
      }
    }
  };
  xhr.onerror = function (e) {
    console.error(xhr.statusText);
  };
  xhr.send(null); }
document.addEventListener('DOMContentLoaded', fn, false);
document.addEventListener

The item (accordion) displays correctly, as in the code here:

https://codepen.io/jakub-czeszejko-sochacki/pen/rNWNwrN

But unfortunately it doesn't work properly as if JS code is not being read for this element. As a result, when you click on the accordion button, the accordion does not open.

Is it even possible for this to work with JS?


Solution

  • Problem solved.

    It turned out that the JS accordion initiation took place before its html was loaded with the line:

    document.getElementById ("accordion"). innerHTML = xhr.responseText;
    

    It was enough to put the initialization code (the accordion opening code) in the function and call this function after the above line of code.