Skip to content

Instantly share code, notes, and snippets.

@chasemccoy
Created March 11, 2015 20:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chasemccoy/4beaff5561ddbf7a82a7 to your computer and use it in GitHub Desktop.
Save chasemccoy/4beaff5561ddbf7a82a7 to your computer and use it in GitHub Desktop.
Change Background Color of CSS Element via Javascript
// Add hex colors you want to cycle through in this array
var colors = ['#E25243', '#00aeef', '#22d5e5', '#B8E986', '#F5A623', '#4A90E2', '#7F92A8', '#61C037', '#B370EF', '#ffdc29', '#FF6858'];
// Calculates the index of the array
// Math.random returns a decimal number between 0 and 1
// array.length returns number of items in array
var randomColor = Math.floor((Math.random()) * colors.length);var changeBackground = function() {
// The element that you want to change needs to have a certain ID, which you can change here
document.getElementById("changeColors").style.backgroundColor = colors[randomColor];
};
changeBackground();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment