简体   繁体   中英

Javascript Array - getting random photo to display when browser loads

Free Code Camp Project

I am working on a tribute page project, and have decided to add a javascript random photo array to the project. This is working fine, but I cant figure out how to get a random photo to appear whenever the browser reloads.

here is my html

<div id="albumCovers"></div>
<button id='randomBut'>View Random Album Covers</button>
<div><img id='movieImg'></div>

here is the javascript

var randomizer = document.getElementById("randomBut");
var randImg = document.getElementById("movieImg");

var movieImages = [
    "all.jpg", 
    "dontgrowup.jpg",
    "everythingSux.jpg",
    "enjoy.jpg",
    "college.jpg",
    "hyper.jpg",
    "cooltobeyou.jpg"
];

randomizer.addEventListener("click", function()
{
    var randNum = Math.floor(Math.random() * movieImages.length) + 0;
    randImg.src = movieImages[randNum];
    randomizer.click();
});

any suggestions?

As pointed out by a user in the comments, you want to utilize DOMContentLoaded event. You can see in the code below I created an init function that gets called upon DOMContentLoaded being fired. The init function's job is to:

1) Make an initial call to the setRandomImage function

2) Set setRandomImage as the click event handler on randomizer

 var randomizer = document.getElementById("randomBut"); var randImg = document.getElementById("movieImg"); var movieImages = [ "all.jpg", "dontgrowup.jpg", "everythingSux.jpg", "enjoy.jpg", "college.jpg", "hyper.jpg", "cooltobeyou.jpg" ]; //When the HTML document has been completely loaded and parsed document.addEventListener("DOMContentLoaded", init); function init() { //Make an inital function call ("when the browser loads") setRandomImage(); //Attach a click event listener to the random button randomizer.addEventListener("click", setRandomImage); } //Put this code in a function since we want to call it multiple times function setRandomImage() { var randNum = Math.floor(Math.random() * movieImages.length) + 0; randImg.src = movieImages[randNum]; //randomizer.click(); -- I dont understand the point of this line of code, so I commented. console.log(`Displaying ${randImg.src}`) } 
 <div id="albumCovers"></div> <button id='randomBut'>View Random Album Covers</button> <div><img id='movieImg'></div> 

Put your random code into a function and call that function on load and button press as shown below. Run the snippet more then once to see the random image generated. Below is a working example.

 var randomizer = document.getElementById("randomBut"); var randImg = document.getElementById("movieImg"); var movieImages = ["https://image.ibb.co/caPP3V/all.jpg", "https://image.ibb.co/btn2OV/dontgrowup.jpg", "https://image.ibb.co/kQoHOV/everything-Sux.jpg", "https://image.ibb.co/c2UP3V/enjoy.jpg", "https://image.ibb.co/ifbFAA/college.jpg", "https://image.ibb.co/fe7Yxq/hyper.jpg", "https://image.ibb.co/dKtj3V/cooltobeyou.jpg"]; randomizer.addEventListener("click", function(){ rans(); }); function rans(){ var randNum = Math.floor(Math.random() * movieImages.length) + 0 randImg.src = movieImages[randNum] ; } 
 #main { margin: 0; } #headline { background: black; margin: auto; width: 100%; } /* The code below makes the main image able to shrink properly for phones, and place the image in its own line. "height: auto;" keeps the original aspect ratio of image */ #logo { max-width: 100%; display: block; margin: auto; height: auto; padding-top: 10px; padding-bottom: 30px; } h1 { color: white; text-align: center; font-family: roboto; padding-bottom: 10px; } #history{ color: black; text-align: center; font-family: roboto; padding-bottom: 10px; } #content { background: white; margin: auto; } #milo { max-width: 100%; display: block; margin: auto; height: 200px; padding-top: 10px; padding-bottom: 30px; } #img-div { background: black; margin: auto; } #img { max-width: 100%; display: block; margin: auto; height: auto; padding-top: 40px; padding-bottom: 30px; } #img-caption { color: white; text-align: center; font-family: roboto; padding-bottom: 30px; } #albumCovers { padding-top: 35px; } #randomBut { display: block; margin: auto; font-size: 25px; } #movieImg { display: block; margin: auto; height: 300px; width: 300px; padding-top: 40px; padding-bottom: 30px; } #wiki { text-align: center; padding-top: 35px; padding-bottom: 35px; } a { text-decoration: none; font-family: roboto; font-weight: 18px; } 
 <head> <title>The Descendents Tribute Page</title> <link rel="stylesheet" type="text/css" href="style.css"> <link href="https://fonts.googleapis.com/css?family=Poppins|Roboto:400,500,700" rel="stylesheet"> </head> <body id="main" onload="rans()"> <div id="main"> <div id="headline"> <img id="logo" src="https://image.ibb.co/fDZPnq/descendents.jpg" alt="descendents" border="0"> <h1 id="title">A tribute to one of the most influential bands in Punk Rock</h1> </div> <div class="content"> <img id="milo" src="https://image.ibb.co/dmcNqA/milo.jpg"> <h1 id="history">HISTORY</h1> <ul id="tribute-info"> <li>1977 - The Descendents was started by original guitarist Frank Naventta</li> <li>1978 - Bill Stevenson would join the band as drummer and became one of the main songwriters. Tony Lombardo joined as bassist.</li> <li>The band's music at the time was described by Stevenson as a "coffee'd-out blend of rock-surf-pop-punk music".</li> <li>1979 - The band enlisted Milo Aukerman as their vocalist, who would go on to become the iconic face of the band.</li> <li>1981 - Fat ep was released</li> <li>1982 - "Milo Goes To College" was released, and is considered one of the most influential albums in punk rock.</li> <li>The band went on hiatus from 1983-1985 while Milo was in college. Bill Stevenson had joined Black Flag in this time. Frank Navetta Burned all his equipment and never returned to the band.</li> <li>1985 - The band reformed and released the album "I Don't Want to Grow Up"</li> <li>1986 - "Enjoy" was released. Karl Alvarez joined as bassist, and Stephen Egerton joined as guitarist.</li> <li>1987 - "All" was released. Milo left the band after touring for the album had finished. The remaining members carried on under the name "All" </li> <li>1996 - The band had reformed with Aukerman, and released the album "Everything Sux" on Epitaph Records</li> <li>1997 - Aukerman left again to pursue his chemistry career</li> <li>2002-2004 - The band began working on a new album in the early 2000s, with Aukerman doing vocal work from a different studio in Delaware.</li> <li>2004 - "Cool to be you" was released on Fat Wreck Chords.</li> <li>2008 - Original guitarist Frank Navetta passed away.</li> <li>2010 - The band reunited again to play occasional one-off shows, but it was never considered a full reunion.</li> <li>2013 - "Filmage" was released, which was a documentary about Descendents and All.</li> <li>2016-present - "Hypercaffium Spazzinate" was released. Aukerman had left his career as a chemist, and the band has since returned to touring full time.</li> </ul> <div id="img-div"> <img id="img" src="https://image.ibb.co/iy08DV/band-Photo.png" alt="band-Photo" border="0"> <div id="img-caption">From left to right: Karl Alvarez (bass), Bill Stevenson (drums), Stephen Egerton (guitar), Milo Aukerman (vocals) </div> </div> <div id="albumCovers"></div> <button id='randomBut'>View Random Album Covers</button> <div><img id='movieImg'></div> </div> <div id="wiki"> <a href="https://en.wikipedia.org/wiki/Descendents" target="_blank">Descendents Wikipedia</a> </div> </div> <script type="text/javascript" src="tribute.js"></script> </body> </html> 

by adding moving the code used in the onclick binding for the button into its own function rans() , having the click event of the button call the function and then adding onload="rans()" to the body tag you get the same functionality and get a random image on page load.

Key code changes: Change this:

randomizer.addEventListener("click", function()
{
    var randNum = Math.floor(Math.random() * movieImages.length) + 0;
    randImg.src = movieImages[randNum];
    randomizer.click();
});

to this:

randomizer.addEventListener("click", function(){
    rans();
  });

function rans(){
  var randNum = Math.floor(Math.random() * movieImages.length) + 0  

    randImg.src = movieImages[randNum] ;
}

and add onload to the body tag:

<body id="main" onload="rans()">

document.addEventListener('DOMContentLoaded',theSameHandlerAsForClick);

change this line

randImg.src = movieImages[randNum] ;

by this one

randImg.setAttribute('src', movieImages[randNum]) ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM