How to share JS code between different scenes?

Hello !
I would like to duplicate one scene to another, with strictly identical appearance and switch from one to another via a button.
Some JS functions are attached to this scene.

Is it possible to duplicate the scene and not the JS functions ?
I could test, in the function, witch scene is active (var scname = hypeDocument.currentSceneName():wink: but do I need to duplicate and rename every single elements/symbols ?
It’s an heavy process for exactly the same behavior in each scene …

Thank by advance for your help

An example of that : 20190901 Box.hype.zip (1003.2 KB)

In the mutationSceneLoad function : I used “pt0”, “pt1” … “pt8” variables, linked as many correspondant displays elements.
If I create a Scene2 with exactly the same elements, I have to create a new set of “pt0-2”, “pt1-2” etc… ?

If you copy/paste or duplicate a scene, the javascript functions themselves won’t get duplicated and will be used by all elements in the new scene.

It sounds like your problem is that you are using unique element IDs for elements. These must be unique across an entire web page, including scenes within the Hype document. So when you duplicate the scene, Hype “intelligently” removes the ID as this would create a conflict.

The solution is to use class names instead of unique element IDs. You an have as many elements with the same class name as you want, and then search for them in a fashion scoped to the scene. The code to do so would look something like:

// get the current scene to use as a scope for the search
var currentSceneElement = document.getElementById(hypeDocument.currentSceneId());

// find the element with the "pt1" class; assumes exactly one match in the scene
var pt1Element = currentSceneElement.getElementsByClassName("pt1")[0]; 

// run your code with this element
observer.observe(pt1Element, config);
3 Likes

Thank you : I will change my code according to your advice and make use of Class Name instead of ID !

1 Like