lundi 20 avril 2015

JS: I am adding images and text to an array and trying to display a random image

I have 2 html text fields:-

(1) allows user to enter Image Url (2) allows user to enter a caption for the image.

I have 2 html buttons:-

(1) one appends image: url, caption to an array. (2) when clicked displays random image out of the array.

Js code:-

    function init() {

    var imageArray = new Array();

    var button1 = document.getElementById("addButtonUrl");
    button1.onclick = handleButtonClick(imageArray);

    var button2 = document.getElementById("randomImgButton");
    button2.onclick = showRandomImg(imageArray);
}



function handleButtonClick(imageArray) {
    // setting 2 variables to get the value entered by the user
    // on the 2 separate text fields: Url, Caption.
    var imgURL = document.getElementById("textfieldUrl").value;
    var imgText = document.getElementById("textfieldCaption").value;

    // evertime the addImgButton is clicked, append (add) the values stored in the variables in the array.
    imageArray.push({url:imgURL, caption: imgText});

    // clear textfield for next image src.
    document.getElementById("textfieldUrl").value = ""; 
    document.getElementById("textfieldCaption").value = "";
}

function showRandomImg(imageArray) { 
    var index = Math.floor(Math.random()*imageArray.length);
    var randomImg = imageArray[index];

}


window.onload = init;

I m not sure how to display the random image along with the associated caption bak on the UI.




Aucun commentaire:

Enregistrer un commentaire