Insert sentence into h2 elements

Insert sentence into h2 elements
0

#1

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...

#2

You will need to run the function.


#3

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


#4

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?


#5

Just run it:

generateQuote();

#6
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.


#7

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…


#8

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();

#9

omg… that makes sense. thanks for your patience.

you guys rock!