JavaScript across Layouts

I mad this simulation graphics using an example I found in the forum.

calculator-1.4.zip (599.4 KB)

It worked great for me but as I wanted to create versions for tablets and smartphones and needed to add Layouts accordingly I couldn’t address the “total” IDs and “sum” IDs.

Is there a not so obvious way to set/address the innerHTML of an object on other Layouts than the main scene?

Here is my attempt for the same calculator with a bunch of other Layouts in it:

calculator-1.5.zip (849.1 KB)

Thanks

Hi @baccioly.
You can address any ID whatever the layout but the trick is that you can’t have several elements with the same ID across your entire Hype document. Which mean that for each layout you have to set a different ID for your total and sum element.

I dealt with this issue in some of my projects, here’s how I manage to keep things as simple as possible.

  • First choose a prefix for each layout (let say D for desktop, M for mobile, T for tablet)
  • For each corresponding element on each layout, give it an ID composed of a common part + the prefix ( for the sum element you’ll get Dsum, Msum, Tsum …)
  • Set a script (triggered on layout load) that detect the layout your’re on (hypeDocument.currentLayoutName) and define a global variable “prefix” accordingly ( i.e : window.prefix=“D” if desktop layout, window.prefix=“M” if mobile …)
  • Then you just have to review your scripts to replace all the occurrences of ‘total’ by window.prefix + ‘total’ and ‘sum’ by window.prefix + ‘sum’ (e.g. hypeDocument.getElementById(window.prefix + ‘total’).innerHTML= …)
2 Likes

Hi there! And thank you for the answer!

Interesting solution!
I was trying using persistent symbols, but I am not too familiar with those.
If you have a simple bare bones example with two layouts please share. =)

I will try and implement it here.

Thanks again!
Best regards!

As you can see it’s really straightforward
adress multi layouts.zip (19.4 KB)

3 Likes

And very elegant!

Thank you again. =)