How to call a hypes script when the user clicks a button defined by html and inserted into a rectangle

I am building the contents that get placed into an object, and its working well. how would I go about assigning a hype script to this:

and have it fire off when the button defined here as a submit button - is pressed?

var chatEntryPoint = '<div class="bg-gray-300 p-4"><input class="flex items-center h-10 w-full rounded px-3 text-sm" type="text" placeholder="Type your message…"><button class="text-sm bg-green-300 p-4 rounded-large" type="submit">Say It</button></div>';

There's a few ways to go about doing this depending on how you are inserting the code and what you want to run. This answer is kind of long, but just because it deals with a little bit of nuance. I'm making the assumptions:

  • the code you have above is something that gets dynamically added via an someElement.innerHTML = chatEntryPoint; type of call.

  • You want to call a Hype function (one defined in the Resources Panel) instead of something more arbitrary/adhoc.

The basic way to make calls to Hype functions is:

HYPE.documents["documentName"].functions().functionName();

But there's a couple points:

  • the documentName is related to the export name, and could even be "index" in the preview environment.
  • Hype functions don't require arguments in the call if you don't use them, but otherwise would take arguments of hypeDocument, element, event

So the easiest way to deal with both of these problems is to make a global variable for the hype document object, especially if you're already in a context where you have a hypeDocument variable, like within an On Scene Load function where you do your setup.

So that could look like:

window.mainHypeDocument = hypeDocument;

Or if you're in a context where it has been loaded but you don't have a hypeDocument, and you know there will only ever be on hypeDocument on the page, you could do:

window.mainHypeDocument = Object.values(HYPE.documents)[0];

Then you can use this in the call by adding an onclick handler with this call:

window.mainHypeDocument.functions().functionName(window.mainHypeDocument, this, event)

(you'll need to change functionName).

So all together it may look like:

	window.mainHypeDocument = Object.values(HYPE.documents)[0];
	var chatEntryPoint = '<div class="bg-gray-300 p-4"><input class="flex items-center h-10 w-full rounded px-3 text-sm" type="text" placeholder="Type your message…"><button class="text-sm bg-green-300 p-4 rounded-large" type="submit" onclick="window.mainHypeDocument.functions().functionName(window.mainHypeDocument, this, event)">Say It</button></div>';
	box.innerHTML = chatEntryPoint;

Does that help?

2 Likes

Yes! That is exactly what I needed. I had successfully called on function from inside a function before, this is the first time I have a better understanding of onClick commands (from inside of Hype) and this explained everything perfectly.

1 Like