I created a very simple script that reads out images of an array and displays them on a page. The array is supposed to hold more than images, but this is how I started. I get function undefined when I run the program I think this is a scope issue and the function can not be accessed when called(?)
<button onclick="myFunction(images)">Try it</button>
<script>
var images = [
{img : " image1.jpg"},
{img : "image2.jpg"}
]
function myFunction(array) {
for ( var i= 0; i < array.length; i++){
var x = document.createElement("IMG");
x.setAttribute("src", array[i].img);
document.body.appendChild(x);
}
</script>
onclickin the HTML, find the button in JS instead (document.querySelector, for instance) and then use.addEventListener("click", function(evt) { ...});.arraydoes not live in your HTML, so don't pretend it's there. Do your JS, in JS. Also, images have theImageobject.var x = new Image(); x.src = ...; document.body.appendChild(x);works fine.