1

I was wondering if I could give multiple divs with the same class name each a unique random colour which then changes every few seconds.

I've been able to do this is javascript but since this will be used on mobile I fear it will be too slow and thus want to use CSS animations. I've experimented with a few things (below) but I haven't figured it out.

Here is the version working with javascript, I want to achieve a similar effect: https://codepen.io/TechTime/pen/ZKdxQK with this javascript:

function randOrd() {
  return Math.round(Math.random()) - 0.5;
}

$(document).ready(function() {
  var klasses = [
    "animated zoomInLeft",
    "animated swing",
    "animated pulse",
    "animated bounceInLeft",
    "animated tada"
  ];
  klasses.sort(randOrd);
  $("#wrapper #box").each(function(i, val) {
    $(this).addClass(klasses[i]);
  });
});

var colorizer = function ( el, min, max ) {

    // @link https://stackoverflow.com/questions/5092808/how-do-i-randomly-generate-html-hex-color-codes-using-javascript
    function getHexColor() {
      return "#000000".replace( /0/g, function () {
        return ( ~~( Math.random() * 16 ) ).toString( 16 );
      } );
    }

    // @link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random

    function getRandomInt( min, max ) {
      return Math.floor( Math.random() * ( max - min + 1 ) ) + min;
    }

    min = undefined == min ? 250 : min;
    max = undefined == max ? 1500 : max;

    var isDefaultColor = true,
        style          = el.style,
        defaultColor   = style.borderBottomColor,
        color;

    return function ( e ) {

      el.offsetWidth; // Reset transition so it can run again.

      color                    = isDefaultColor ? getHexColor() : defaultColor;
      isDefaultColor           = !isDefaultColor;
      style.borderBottomColor  = color;
      style.transitionDuration = ( getRandomInt( min, max ) ) + 'ms';

    };

  },
  colorizeAll = function ( els, min, max ) {

    var arr = [].slice.call( els ); // To Array from NodeList.

    arr = arr.map( function( el ) {

        var colorized = colorizer( el, min, max );

      el.addEventListener( 'transitionend', colorized );

      return colorized;

    } );

    return function () {
        arr.map( function ( colorized ) {
            colorized();
      } );
    };

  },
  tris = document.querySelectorAll( '.triangle-up > div' ),
  all  = colorizeAll( tris, 750, 2000 );

// Kick it off!
all();




var colorizer2 = function ( el2, min2, max2 ) {

    // @link https://stackoverflow.com/questions/5092808/how-do-i-randomly-generate-html-hex-color-codes-using-javascript
    function getHexColor2() {
      return "#000000".replace( /0/g, function () {
        return ( ~~( Math.random() * 16 ) ).toString( 16 );
      } );
    }

    // @link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
    function getRandomInt2( min2, max2 ) {
      return Math.floor( Math.random() * ( max2 - min2 + 1 ) ) + min2;
    }

    min2 = undefined == min2 ? 150 : min2;
    max2 = undefined == max2 ? 5500 : max2;

    var isDefaultColor2 = true,
        style2          = el2.style,
        defaultColor2   = style2.borderTopColor,
        color;

    return function ( e ) {

      el2.offsetWidth; // Reset transition so it can run again.

      color                    = isDefaultColor2 ? getHexColor2() : defaultColor2;
      isDefaultColor2           = !isDefaultColor2;
      style2.borderTopColor  = color;
      style2.transitionDuration = ( getRandomInt2( min2, max2 ) ) + 'ms';

    };

  },
  colorizeAll2 = function ( els, min, max ) {

    var arr = [].slice.call( els ); // To Array from NodeList.

    arr = arr.map( function( el ) {

        var colorized2 = colorizer2( el, min, max );

      el.addEventListener( 'transitionend', colorized2 );

      return colorized2;

    } );

    return function () {
        arr.map( function ( colorized2 ) {
            colorized2();
      } );
    };

  },
  tris2 = document.querySelectorAll( '.triangle-down > div' ),
  all2  = colorizeAll2( tris2, 750, 2000 );

// Kick it off!
all2();


if (
  /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
    navigator.userAgent
  )
) {
 //add stuff
  $("#zewrapper").css("max-height", "700px");
}

Experiments (failed): https://jsfiddle.net/rc3a9zgv/ uses this scss:

body {
  background-color: #FFF;
  background: #bfbfbf;
  overflow-x: hidden;
  --random-colors: 2;

}
:root {
  --random-colors: 2;
}
@mixin random-color($selector) {
  #{$selector}: unquote("rgba(#{var(--random-colors)}, #{--random-colors}, #{--random-colors}, #{random(100)/100})");
}
seven-phases-max
  • 11,765
  • 1
  • 45
  • 57
Techtime
  • 27
  • 5
  • See https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Animations/Using_CSS_animations – seven-phases-max Jun 01 '17 at 19:32
  • So CSS isn't meant for something like randomly color changing – Techtime Jun 02 '17 at 15:08
  • No idea why you decided that. My link above is meant to illustrate how to create animations in CSS in general (including changing a color every few second using a list of any colors including random). Your code above does not make any sense since CSS animations are created via `@keyframes` and not via assigning a list of colors to a single property like you've tried. – seven-phases-max Jun 02 '17 at 16:59
  • Sorry for misinterpreting Where does it mention changing the color randomly in that link? I haven't been able to find it... – Techtime Jun 02 '17 at 17:14
  • Simply use whatever `random` facility of your CSS preprocessor (e.g. Sass) to set the color property of interest in `@keyframes`. – seven-phases-max Jun 02 '17 at 17:18
  • (In general though, "randomness" in visual styles does not make sense too, why don't you want just a list of predefined *pleasant* colors? But yes, random are still possible). – seven-phases-max Jun 02 '17 at 17:20
  • 1
    The problem with using a random facility from a CSS preprocessor is that once it has chosen something random, it stays that way. Meaning all elements using that random facility will recieve the same random color. My situation is having multiple divs of the same class and id each recieve a unique color – Techtime Jun 02 '17 at 17:24
  • See [example](https://codepen.io/seven-phases-max/pen/WONQGB?editors=1100) (in Less). If you mean that you can target *a random element id* with CSS, then yes, you can't (CSS can only target predefined set of classes/tags/ids of course), but yet again I'd simply use a list of predefined ids (*if* performance is your goal, it does not make sense to really have unique color for *each* new element, it's fine if color is repeated after 10-20-100 (put your count) elements - see another [example](https://codepen.io/seven-phases-max/pen/tKdAm?editors=1100)). – seven-phases-max Jun 02 '17 at 18:20
  • I mean once it choses a random number when it is repeated it uses the same number – Techtime Jun 02 '17 at 18:32
  • *it choses a random number when it is repeated it uses the same number* - sorry I can't understand what this means (probably I could if I tried to understand what you JS code does but it's too large and too cryptic to bother - sorry again). – seven-phases-max Jun 02 '17 at 18:35
  • random in sass is like randomly choosing the name of a main character in a story. it's only random when written. it doesn't change. In other words, as soon as the CSS is processed, randomization is over. That number is locked at that value forever (i.e. until the preprocessor runs again).It's not like a random number in JavaScript (e.g. Math.random()) where that random number is generated when the JavaScript runs. – Techtime Jun 02 '17 at 18:47
  • Ah, that - yes (I assumed you considered that from the starting point). – seven-phases-max Jun 02 '17 at 22:04

0 Answers0