Show random picture

Hello!
I'm trying to display a random image on click. I found the code, pasted it in, but it doesn't work. I don't know javascript and this is a problem for me. Please help me understand how to do it.

https://drive.google.com/drive/folders/1MXDf52oq7HAM6Y5ujj3rKOe9fFCn-4_J?usp=sharing
:rotating_light: Please note that we can only address JavaScript questions and issues in the context of Tumult Hype, so please attach a Hype document so others can dig into what you have so far.

Doing it the Hype way.

You just need a Hype button and an image on scene.
Then use the code as such.

var imagesArray = ["11.jpg", "22.jpg", "33.jpg", "44.jpg", "55.jpg", "66.jpg"];

 
    var num = Math.floor(Math.random() * imagesArray.length); // 0...6
     
   var imageBox_ =  hypeDocument.getElementById('imageBox')
    
   hypeDocument.setElementProperty(imageBox_, 'background-image', '${resourcesFolderName}/' + imagesArray[num])  ;

picrandom 2.hype.zip (42.5 KB)

If you really need it all inside a Table and using a form! let me know.

3 Likes

Hi! There's a few things that you will need to do to get this document working correctly:

  1. You currently have the HTML code on the scene in an HTML Widget. The HTML Widget is an <iframe> element, which means everything in it is isolated from the rest of the page. Since you're calling into code that is in the hype page's scope, you will not want to use this element type. Instead, you will want to use a Rectangle element (a <div> under-the-hood) and then you can remove all styling and still edit the inner html the same way.

  2. You will need to select your images and in the Resources Library uncheck "Automatically optimize when Exporting". The optimization process is at odds with accessing images via code, since it may change the filenames which would not match up.

  3. Your untitledFunction() that has the code is not called by anything, so your function is not setup properly. You should add an On Scene Load action in the Scene Inspector that is set to Run JavaScript… with this function.

  4. Your code is incorrect in a couple ways. First, the array that lists the images in not properly formatted and would cause a syntax error. Second, your displayImage() function is declared within the scope of the untitledFunction() and therefore won't be accessible via the button click. To resolve this, you would make the function a global variable by setting it as window.displayImage = function () { /*... contents */ }

I've made these changes, and now it appears to work.

picrandom-fixed.hype.zip (36.1 KB)

Of course what you plan to do on the future may require further changes... so it may also be worth your while to spend some time with learning JavaScript, as it is opens up many interactivity possibilities!

2 Likes

Oh, it looks like @MarkHunte beat me to a reply; I like that his answer used more Hype-specific ways to do it :slight_smile:.

2 Likes

Thank you very much!

2 Likes