Search code examples
javascriptcsscss-gradients

How can I set different gradients as background, each time user refreshes?


I'm working on a bootstrap based webpage and in my CSS file I have the following code:

body {
  height: 100%;
  background: #3a7bd5; /* fallback for old browsers */
  background: -webkit-linear-gradient(to left, #3a7bd5 , #3a6073); /* Chrome 10-25, Safari 5.1-6 */
  background: linear-gradient(to left, #3a7bd5 , #3a6073); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
}

it applies gradient as a background to my page, however I have also two other gradients:

background: #114357; /* fallback for old browsers */
background: -webkit-linear-gradient(to left, #114357 , #F29492); /* Chrome 10-25, Safari 5.1-6 */
background: linear-gradient(to left, #114357 , #F29492); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */

and

background: #eacda3; /* fallback for old browsers */
background: -webkit-linear-gradient(to left, #eacda3 , #d6ae7b); /* Chrome 10-25, Safari 5.1-6 */
background: linear-gradient(to left, #eacda3 , #d6ae7b); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */

and now I want to apply one of those 3 gradients randomly when user refreshes the page (so e.g. first he sees the 2nd gradient, then he refreshes the page and sees the 3rd gradient, etc.).

How can I achieve this effect?


Solution

  • After the page loads, add a random class to the <body> element using JavaScript, and assign different gradients to different classes.

    document.body.classList.add('gradient' + [1, 2, 3][Math.floor(Math.random() * 3)])
    body {
      height: 100%;
    }
    body.gradient1 {
      background: #3a7bd5; /* fallback for old browsers */
      background: -webkit-linear-gradient(to left, #3a7bd5 , #3a6073); /* Chrome 10-25, Safari 5.1-6 */
      background: linear-gradient(to left, #3a7bd5 , #3a6073); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
    }
    body.gradient2 {
      background: #114357; /* fallback for old browsers */
      background: -webkit-linear-gradient(to left, #114357 , #F29492); /* Chrome 10-25, Safari 5.1-6 */
      background: linear-gradient(to left, #114357 , #F29492); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
    
    }
    body.gradient3 {
      background: #eacda3; /* fallback for old browsers */
      background: -webkit-linear-gradient(to left, #eacda3 , #d6ae7b); /* Chrome 10-25, Safari 5.1-6 */
      background: linear-gradient(to left, #eacda3 , #d6ae7b); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
    }