Insert sentence into h2 elements

hey everybody,

im trying to create a random quote generator that cycles through an array of objects, getting stuck though when trying to take the random quote and insert it back into the h2 element using the .innerHTML…

can anybody spot the problem here is the code and also my codepen

var movies = [
{ 	
	movie: "The Big Lebawski",
	quote: "I don't roll on the sabbath"
},
{
	movie: "Superbad",
	quote: "Mclovin, who are you Seal?"

},
{
	movie: "Lord of the Rings",
	quote: "One ring to rule them all"
}
];


function generateQuote(){

	let newQuote = movies[Math.floor(Math.random()*movies.length)].quote;
	document.getElementById('quote').innerHTML = newQuote; 
};

// h2 element id is quote...

You will need to run the function.

@BenGitter is right. Your button doesn’t do anything. Look up the onclick attribute.

i just wanted it to populate the h2 element as soon as the page loaded, not when you click the button…

the button i was gonna use when they type in what movie they think its from. is there a way to run the function when the page loads?

Just run it:

generateQuote();
window.onload = function () {
    //Run Code Here :3
}

Or you can just run it like Ben said. If you go that route though make sure the script tag is at the end of body tag so that the javascript actually has an h2 tag to select.

just run it in the HTML? how would that look. i know this is beginner material, but im having a mental colapse right now.

sorry im a bit lost…

No problem.

You would run it inside the JS file. Your total JS would look like this:

var movies = [
{ 	
	movie: "The Big Lebawski",
	quote: "I don't roll on the sabbath"
},
{
	movie: "Superbad",
	quote: "Mclovin, who are you Seal?"

},
{
	movie: "Lord of the Rings",
	quote: "One ring to rule them all"
}
];


function generateQuote(){

	let newQuote = movies[Math.floor(Math.random()*movies.length)].quote;
	document.getElementById('quote').innerHTML = newQuote; 
};

generateQuote();

omg… that makes sense. thanks for your patience.

you guys rock!

1 Like