Randomizing images in JavaScript

In Control My Panic, there is a distraction picture part where a picture is displayed with text underneath, asking a question to the user. The picture and question are used to distract the user. I gathered a few different pictures so they would randomize for the user each time they went to use Control My Panic, as if they only saw the same photo every time, it would be less effective.

Through JavaScript, I had to figure out how to randomize images whenever the page is reloaded. I knew it would probably done through an array, but wasn’t sure how to properly do it. (JS is not my strong suit!)

I find a nice tutorial on Dynamic Web Coding that did exactly what I was looking for. I had to create an array, then create a function and then call the function in the section of my HTML I wanted it to be displayed.

array1

Creating array with the images

array2

Function getRandomImage

array3

Calling the function in the HTML

I tried to add this to my script.js file, but it wouldn’t work. When I added the code into the head of my HTML file, it worked.. dunno why it wouldn’t work in my JS file.

I had the images randomizing, but I needed text to be displayed specific to the image that was randomized. After searching online, I found out that I had to add another array for the text and then get the values from that array.

array.PNG

New array and changed function

Now the images randomize and the matching text shows. I just need to figure out how to style the text!

array4.png

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s