0

I am using ejs to dynamically generate buttons, which have onclick functions which live inside a remote script tag. The remote script runs, but when the buttons are clicked, the function cannot be found.

collection:148 Uncaught ReferenceError: viewPanoscape is not defined at HTMLButtonElement.onclick

My ejs file

<body>
      <tbody>
            <% let c=1 %>
            <% collection.forEach(function(ps){ %> 
            <tr>
                <th scope="row"><%=c%></th>
                <td><button type="button" class="btn btn-primary" onclick="viewPanoscape()">View</button></td>
            <%c++%>
            </tr>
      </tbody>

my remote collection.js file

 function viewPanoscape(e){
    console.log('viewPanoscape', e);
}

window.onload = function() {
  viewPanoscape("test");
}

I know the script loads as the console prints

viewPanoscape test

But when I click the button, it does not see the function. Clearly this is a scoping problem, but I don't understand how the best way to include a function that ejs can see.

Thomas Williams
  • 842
  • 6
  • 13

1 Answers1

0

I found a solution using addEventListener() instead of onclick

    window.addEventListener('load', function()
{
  console.log('window loaded')
  const block = document.querySelector('.product-container');
  // Create a function that shows the index of the child of the parent block
  for (let i=0, len = block.children.length; i < len; i++){
      (function(index){
        block.children[i].onclick = function(e) {
          if (e.target && e.target.classList.contains('viewbutton')){
            console.log(e.target,e.target.classList);
          }
        }
      })(i);
  }
})

with help from this post JavaScript onclick event gets the wrong id from dynamically generated html element

Thomas Williams
  • 842
  • 6
  • 13