How to store images in an array?7

I have 3 image files: a1.jpg,. a2.jpg, and a3.jpg.
I have two questions:

1.How do I store/assign these files to an array ’pic’?
2. How do I display a2.jpg on click of the button ‘press me’?

The 3 image files are in the ‘park’ folder which is in the same fodder as the html file.
Thank you.

This is currently beyond the scope of what’s taught in Grasshopper since you’re working directly with an html file, but this code would do what you’re asking.

    <button id="myButton" type="button">press me</button>
    <img id="myImage" src="a1.jpg">
    <script type="text/javascript">
        let pic = ['a1.jpg', 'a2.jpg', 'a3.jpg'];
        let imageNumber = 0;
        document.getElementById("myButton").addEventListener('click', changeImage);
        function changeImage() {
            imageNumber = (imageNumber + 1) % pic.length;
            document.getElementById("myImage").src = pic[imageNumber];

I did not request this

1 Like

Thank you very much.
The code is, at this point in time, beyond my comprehension, but it certainly works the way I want it to when the 3 image files are in the same folder as the html file.
How should I change the code if the 3 image files are stored in the sub-folder ‘park’?
Thank you.

I think you’ve subscribed to my posts, or all posts on the forum. At the bottom of the email there should be a link that says, “To unsubscribe from these emails, click here.”


1 Like

Instead of 'a1.jpg', you would use 'park/a1.jpg'. You would also need to change all 4 strings that have .jpg in them.

You could organize this a bit by breaking up the string into different parts:

let path = 'park/'
let name = 'a1'
let type = '.jpg'

and then combining the parts: path + name + type. This way you can just change the value of name to get the location of the next picture. You could even just do 'park/a' + imageNumber + '.jpg' if you put it in the right place and are careful about the value of imageNumber.

You might find it helpful to search MDN for other html information.



Thank you very much for your help. You are so very supportive.

1 Like