All Glory to the Hypnotoad!

Show me the glory!

hypnotoad

Ok, I get it. Make it stop.

When I saw a really neat one line random color generator in a blog post, I saw it as an opportunity to glorify the hynotoad. This is the magic part:


(~~(Math.random()*(1<<24))).toString(16) 

In that line, ".toString(16)" gives us a hexadecimal value. We need to constrain our random numbers between 0 and ffffff, hexadecimally speaking, or 16777215 when converted to an integer. "1<<24" is a fancy and short way to achieve 16777216 using bitwise operators. The double tilde is a shorthand to lop off the decimal places that the call to "Math.random()" gives us. It could also have been achieved using "parseInt" on our random value.


(parseInt(Math.random()*(16777216))).toString(16)

This works just as well, but isn't nearly as cool looking.

Dropping our random color generator into a setInterval produces pleasing results.


setInterval(function(){
  var toads = document.querySelectorAll('.hypnotoad');
  [].forEach.call(toads, function(toad){
     toad.style.backgroundColor = "#"+(~~(Math.random()*(1&lt;&lt;24))).toString(16);
  });
}, 80);

Apply your hypnotoad class to any element you want to begin glorification.

Here's a link to a codepen, if you like that sort of thing

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.