Search code examples
javascriptjqueryhtmlcsscodepen

How can I make an array of image urls, append them to an existing array, and get the page to load the image using jQuery?


I am trying to add images to my random array. Basically the idea is this random generator tells you what movie you should watch and I am trying to figure out how to add images of the move underneath the title. I think possibly the best way might be to create a second array with image urls, and append them to the existing array using + and brackets. I just am not sure how to get the script to load the images. Here is my codepen: https://codepen.io/McComb/pen/qVPOQO

HTML

<head>  
<link 
href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-
awesome.min.css" 
rel="stylesheet"  type='text/css'>  
<h1 style="text-align: center; color: red; font-family: verdana; font-
weight: bold;">WHAT CHRISTMAS MOVIE SHOULD I WATCH?</h1>
</head>
<body>
<div class="container">
<div id="generator" style="padding-top: 10px;">
<p>
<i class="fa fa-snowflake-o fa-5x spin"></i>
<i class="fa fa-gift fa-5x spin"></i>
<i class="fa fa-tree fa-5x spin"></i>

</p>

<input type="button" id="btnSearch" value="What Christmas Movie Should I 
Watch?" onclick="GetValue();" />
<p id="message"></p>
</div>
<div id="picture"></div>
</div>

JQuery

 function GetValue()
{
var myarray= new Array("The Santa Claus", "Just Friends","Home Alone", "Home 
Alone 2","Serendipity","Love Actually","Elf","Christmas Vacation","A 
Christmas Story","The Grinch","Jingle All the Way","Rudolph the Red-Nosed 
Reindeer","Ernest Saves Christmas","Frosty the Snowman","The Muppet 
Christmas Carol","The Nightmare Before Christmas","Jesus of Nazareth 
1977","Bad Santa");
var random = myarray[Math.floor(Math.random() * myarray.length)];
//alert(random);
document.getElementById("message").innerHTML=random;
}

Solution

  • The easiest way to achieve what you want is to save objects as opposed to strings in your array. That way, you can create objects that have a title field and an imageUrl field like so:

    var myarray= new Array(
        {
            title: "The Santa Claus",
            imageUrl: "https://upload.wikimedia.org/wikipedia/en/thumb/e/e7/Video-x-generic.svg/90px-Video-x-generic.svg.png"
        }, 
        {
            title: "Random Movie",
            imageUrl: "https://upload.wikimedia.org/wikipedia/commons/thumb/a/ad/BolexH16.jpg/220px-BolexH16.jpg"
        }, 
        // you can add as many comma-separated objects as you want
    );
    

    Add an img element to your HTML and give it id picture. In your JS, you can set your movie's title and image like so:

    document.getElementById("message").innerHTML=random.title;
    
    // the element with id picture is an image element
    document.getElementById("picture").src = random.imageUrl;
    

    I have modified your codepen here with the proposed changes.