External JS event listener

Hello,

I have a fully functional hype build, but I'd like to add a few console logs on click of certain buttons.
I wouldn't like to go back to the build and add console logs on click from there.
I'm aiming to add some javascript to the HTML file where my hype build sits, and do it from there, then I can just delete this code in the future without having to rebuild the hype creation.

Unfortunately, I'm unable to add an event listener successfully.

  document.getElementById('button1').addEventListener('mouseup', function () {
    console.log('button 1 clicked');
  });

I tried "click" and "mouseup" but it doesn't seem to work...

The element isn't in an iframe so I don't know why it won't work. Anyone has any idea?

Thanks

You can’t add event listener to HTML that is probably not in initialized. Maybe try putting your event listeners onto into into a page/DOM, document or scene load function. Another way would be to assign a listener to .HYPE_document and rely on event bubbling. Could always also use Hype Action Events that also works with event bubbling.

If you'd like more help, it would be useful if you can post a zip of your .hype document so we can see exactly where you are placing that code fragment and the general structure of your document. There's a lot of different possibilities on why it may not work as expected :slight_smile:.

1 Like

I am reading this as you are adding temporary code to the exported HTML file's head.

if that is the case then you can wrap the code in an on load function, which will wait for the document to load and then run the code within.

Hype has it's own native API for this. You can add this code as needed to the exported HTML file's head.

Note I have used HypeDocument in place of document.
Now the HypeDocument has loaded we have access to it.

You can use either document or HypeDocument at this stage but using the HypeDocument on hypes element may give some advantages if you want to do more.

  <script type="text/javascript"> function myCallback(hypeDocument, element, event){ 
 
hypeDocument.getElementById("button1").addEventListener("click", function(){
   console.log('button 1 clicked');
});

  } 

if("HYPE_eventListeners" in window === false) {
window.HYPE_eventListeners = Array();
}

window.HYPE_eventListeners.push({"type":"HypeDocumentLoad", "callback":myCallback});
</script>
1 Like