Javascript array and changing an image with button

Javascript: iteration to change images in DOM

Purpose:
For the next experiment, it was trying to change an image by button click, and surf through the array in my javascript file.

Setup:
Remember all files are in the same folder.
To replicate this experiment locally on your browser, have your image files, your HTML and your JS in the same folder, replace the file names in the image_array [] with your file names.  In my code, you'll see the image paths for my images. Double click that index.html file and see the code run. 


*Note about frameworks and non-local use of this code*
In an actual web app, with something like Django, the images would be in static / images,  the html, in templates, and the javascript in the static/js.


But why?

It's helpful to me to create these little projects so I can explore how things work.
I'm sharing as I learn so that maybe this method would be useful to others. 

Notes

Next experiment I will evolve the style more, and try to retrieve the image path from an object constant instead.

The incrementor/counter once again came in quite handy. 
Making it work first is the goal, then moving the codes into the app.

 Video:








GIMME THE CODE

index.html



<!DOCTYPE html>

<html>
<head>
<title>Exercise 2 Arrays</title>
 <script type="text/javascript" src="ex2.js"></script>
  </head>
  <!-- #91cac5 == greyish teal-->
  <body id="Main_Body" style="background:grey;">
    <br>
    <br>


  <h1> This is the browser opened page </h1>
  <br>

  <div style="display: inline-block; margin-left: 25%; margin-right: 25%;">
    <button id="mybutton" onclick="myFunction()">Test the code</button>
    <img id="myImages" style="display: block; width: 400px; height: 400px; border: solid;" src="/home/nellie/Desktop/browser test/image1.png">
  </div>



  </body>
  </html>



ex2.js



 // JavaScript file for experiment 2  => arrays



const image_array = [
                     "/home/nellie/Desktop/browser test/image1.png",
                     "/home/nellie/Desktop/browser test/image2.png",
                     "/home/nellie/Desktop/browser test/image3.jpg",
                     "/home/nellie/Desktop/browser test/image4.png"
                    ];
var place = 0;

function incrementor(n){
  max = image_array.length - 1;
 
  if( n < max){
    return n + 1;
}
  else{
    return 0;
  }
}


function myFunction(){
  var image_element = document.getElementById("myImages");
  place = incrementor(place);
  var new_image = image_array[place];
  image_element.src = new_image;
 
};










 

Comments

Popular posts from this blog

JavaScript Ascii animation with while loops and console.log

playing with trigonometry sin in pygame

JavaScript and a Matrix