Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Sahan Balasuriya
Sahan Balasuriya
10,115 Points

not sure what java script to use

I have an idea for a site that i want to make just for fun. when the site is opened there will be a random background and a random famous quote. so every time the page refreshes i want to the background and the quote to change. how can i do that lets say if i already downloaded a bunch of backgrounds and saved a lot of quotes

1 Answer

Maybe try this?

<body>
    <h1>
        Quotes Go Here
    </h1>
</body>
//Create your arrays
var backgroundImages = ['red','blue','green','yellow'];
var quotes = ['Quote one', 'Quote two', 'Quote three', 'Quote four'];

//Create a function to return a random number
var rand = function() {
    return Math.floor(Math.random()*4); //Change the number 4 for the amount of quotes/backgrounds. you can also use .length to check how many elements in array
};

//Use jquery to do the job
$(document).ready(function() {
    $('body').css('background', backgroundImages[rand()]);
    $('body h1').text(quotes[rand()]);
});