Widget won't render from JavaScript EventListener

Viewed 29

I'm trying to dynamically load an external widget from an eventlistener that listens to changes in a dropdown menu. When I simply load the widget from the HTML file it works just fine. When I use the eventlistener it does not load the widget and gets stuck on the loading spinner - so the element is added to the element tree but doesn't fully load. The dropdown menu links provide a data attribute which then changes the id of the "data-league" field in the widget.

The widget:

 <div id="wg-api-football-standings"
  data-host="api-football-v1.p.rapidapi.com"
  data-league="383"
  data-team=""
  data-season="2021"
  data-key="0ecaca"
  data-theme="grey"
  data-show-errors="false"
  class="api_football_loader">
</div>

The eventlistener:

  // EventListener set on the dropdown menu
  leagueSelector.addEventListener('click', function(e) {

    // get the id from the dropdown menu data attribute 
    const leagueId = e.target.getAttribute("data-league-id");
   
    // the markup with the new id inserted in the "data-league" field
    const markup = `<div id="wg-api-football-standings"
    data-host="api-football-v1.p.rapidapi.com"
    data-league="${leagueId}"
    data-team=""
    data-season="2021"
    data-key="0ecaca"
    data-theme="grey"
    data-show-errors="false"
    class="api_football_loader">
  </div>`

    // clear the widget container and then insert the new markup
    tableContainer.innerHTML = '';
    tableContainer.insertAdjacentHTML('afterbegin', markup);
  });
1 Answers

The library you're using listens to the DOMContentLoaded event, so it will load the widgets when the page loads. You can "force" it to reload by dispatching a DOMContentLoaded event on the window, just keep in mind that if you have anything that listens for that event it will trigger too.

leagueSelector.addEventListener('click', function(e) {
    // Your code...

    window.dispatchEvent(new Event('DOMContentLoaded'));
});
Related