)
}
}
)
(
}
{
)
)
(
)
(
(
{
}
)
(
)
}
)
)
{
(
(
)
)
}
)
(
}

Bad PI Approximation

  1. let inside = 0;
  2. let precision = 1e6;
  3. for (let i = 0; i < precision; i++){
  4.   const xp = 0.5 - Math.random();
  5.   const yp = 0.5 - Math.random();
  6.   if (Math.sqrt(xp * xp + yp * yp) < 0.5) {
  7.     inside++;
  8.   }
  9. }
  10. console.log(inside / precision * 4);

This is a funny one, someone described this to me once and I coded it up over on actionsnippet.

Super Simple Seeded Random

  1. let _seed = 1234567;
  2.  
  3. // Deterministic pseudo-random float in the interval [ 0, 1 ]
  4. function seededRandom( s ) {
  5.   if ( s !== undefined ) _seed = s % 2147483647;
  6.  
  7.   // Park-Miller algorithm
  8.   _seed = _seed * 16807 % 2147483647;
  9.   return ( _seed - 1 ) / 2147483646;
  10. }

Straight from the THREE.js source code – a fun and simple seeded random. The best libraries are always filled with gems like this…

If I were going to use this I would do a couple things out of pure preference:

  1. let seed = 1234567;
  2.  
  3. const setSeed = newSeed => seed = newSeed
  4. function seededRand() {
  5.   // Park-Miller algorithm
  6.   seed *= 16807 % 0x7fffffff;
  7.   return (seed - 1) / 0x7fffffff;
  8. }
  9.  
  10. // try it out:
  11.  
  12. console.log('one', seededRand());
  13. console.log('two', seededRand());
  14. console.log('three', seededRand());
  15.  
  16. seed = 9999
  17. console.log('one new seed', seededRand());
  18. console.log('one new seed', seededRand());
  19.  
  20. seed = 1234567;
  21. console.log('one old seed', seededRand());

If you’re wondering about what this is doing… read more about it here.

Bring Node to Top

  1. myEl.parentNode.appendChild(myEl);

This will make an element the top most of all of its siblings…

  1. document.body.innerHTML += `
  2. <div>
  3.   <button>one</button>
  4.   <button>two</button>
  5.   <button>three</button>
  6.   <button>four</button>
  7. </div>
  8. <style>
  9.   button { display: block; cursor: pointer; }
  10. </style>
  11. `;
  12. document.addEventListener('click', e => {
  13.   if (e.target.tagName === 'BUTTON') {
  14.     e.target.parentNode.appendChild(e.target);
  15.   }
  16. });

Clicking on any button will bring it to the top most position within its parent.

// dom // javascript // tricks // ui

Letter Particles With Keyboard

  1. const Key = {
  2.   LEFT: 37,
  3.   UP: 38,
  4.   RIGHT: 39,
  5.   DOWN: 40,
  6.   disabled: false
  7. };
  8.  
  9. const keyDown = {};
  10.  
  11. function setupKeys() {
  12.   const alph = 'abcdefghijklmnopqrstuvwxyz'.split('');
  13.   const keys = {};
  14.   const aKey = 65;
  15.   alph.forEach((letter, i) => {
  16.     const idx = aKey + i;
  17.     keyDown[idx] = false;
  18.     Key[letter.toUpperCase()] = idx;
  19.   });
  20.  
  21.   keyDown.allLetters = () => {
  22.     const lettersDown = alph.filter(
  23.       letter => keyDown[Key[letter.toUpperCase()]]
  24.     );
  25.     return lettersDown;
  26.   };
  27.  
  28.   document.addEventListener('keydown', e => {
  29.     e.preventDefault();
  30.     if (!Key.disabled) {
  31.       keyDown[e.which] = true;
  32.     }
  33.   });
  34.  
  35.   document.addEventListener('keyup', e => {
  36.     e.preventDefault();
  37.     keyDown[e.which] = false;
  38.   });
  39. }
  40.  
  41. setupKeys();
  42.  
  43. // later:
  44.  
  45. const dots = {};
  46. let id = 0;
  47. function dot(letter = '') {
  48.   const el = document.createElement('div');
  49.   el.innerHTML = letter;
  50.   const size = 20;
  51.   const scale = 1 + Math.random() * 2;
  52.   const vel = (2 - scale / 2) / 4;
  53.   let x = innerWidth / 2 - size;
  54.   let y = innerHeight / 2 - size;
  55.   let vx = Math.random() * 6 - 3;
  56.   let vy = Math.random() * 6 - 3;
  57.   let life = 0;
  58.   let maxLife = Math.floor(50 + Math.random() * 30);
  59.   Object.assign(el.style, {
  60.     position: 'absolute',
  61.     left: 0,
  62.     top: 0,
  63.     transform: `translate3d(${x}px, ${y}px)`,
  64.     borderRadius: '500px',
  65.     background: 'red',
  66.     width: `${size}px`,
  67.     fontFamily: 'sans-serif',
  68.     textAlign: 'center',
  69.     color: 'white'
  70.   });
  71.  
  72.   id++;
  73.  
  74.   let props = {
  75.     el,
  76.     id,
  77.     right() {
  78.       vx += vel;
  79.     },
  80.     left() {
  81.       vx -= vel;
  82.     },
  83.     down() {
  84.       vy += vel;
  85.     },
  86.     up() {
  87.       vy -= vel;
  88.     },
  89.     run() {
  90.       life++;
  91.       if (life === maxLife) {
  92.         document.body.removeChild(dots[props.id].el);
  93.         delete dots[props.id];
  94.       }
  95.       x += vx;
  96.       y += vy;
  97.       vx *= 0.999;
  98.       vy *= 0.999;
  99.       el.style.transform = `translate(${x}px, ${y}px) scale(${scale}) `;
  100.     }
  101.   };
  102.   dots[id] = props;
  103.   document.body.appendChild(el);
  104. }
  105.  
  106. function loop() {
  107.   keyDown.allLetters().forEach(letter => {
  108.     dot(letter);
  109.   });
  110.  
  111.   for (let i in dots) {
  112.     dots[i].run();
  113.   }
  114.  
  115.   if (keyDown[Key.LEFT]) {
  116.     for (let i in dots) {
  117.       dots[i].left();
  118.     }
  119.   }
  120.  
  121.   if (keyDown[Key.DOWN]) {
  122.     for (let i in dots) {
  123.       dots[i].down();
  124.     }
  125.   }
  126.  
  127.   if (keyDown[Key.RIGHT]) {
  128.     for (let i in dots) {
  129.       dots[i].right();
  130.     }
  131.   }
  132.  
  133.   if (keyDown[Key.UP]) {
  134.     for (let i in dots) {
  135.       dots[i].up();
  136.     }
  137.   }
  138.  
  139.   requestAnimationFrame(loop);
  140. }
  141. loop();
  142.  
  143. const info = document.createElement('div')
  144. info.innerHTML = 'click here, then type letters and use arrow keys'
  145. document.body.appendChild(info)

A demo showing how to use the keyboard snippet from yesterday. Also added a function to obtain an array of all currently pressed letter keys

// animation // javascript // keys // math // random // tricks // ui

Easy Keyboard Controls JavaScript

  1. const Key = {
  2.   LEFT: 37,
  3.   UP: 38,
  4.   RIGHT: 39,
  5.   DOWN: 40,
  6.   disabled: false
  7. }
  8.  
  9. const keyDown = {}
  10.  
  11. function setupKeys() {
  12.   const alph = 'abcdefghijklmnopqrstuvwxyz'.split('')
  13.   const keys = {}
  14.   const aKey = 65
  15.   alph.forEach((letter, i) => {
  16.     const idx = aKey + i
  17.     keyDown[idx] = false
  18.     Key[letter.toUpperCase()] = idx
  19.   })
  20.  
  21.   document.addEventListener('keydown', e => {
  22.     if (!Key.disabled) {
  23.       keyDown[e.which] = true
  24.     }
  25.   })
  26.  
  27.   document.addEventListener('keyup', e => {
  28.     keyDown[e.which] = false
  29.   })
  30. }
  31.  
  32. setupKeys()
  33.  
  34. // later:
  35.  
  36. function loop() {
  37.   if (keyDown[Key.LEFT]) {
  38.     console.log('left')
  39.   }
  40.   if (keyDown[Key.UP]) {
  41.     console.log('up')
  42.   }
  43.   if (keyDown[Key.C] || keyDown[Key.D]) {
  44.     console.log('c or d key')
  45.   }
  46.   requestAnimationFrame(loop)
  47. }
  48. loop()
  49.  
  50. const info = document.createElement('div')
  51. info.innerHTML = 'click to give focus - then use C, D or LEFT keys.'
  52. document.body.appendChild(info)

Use a desktop and go into fullscreen when using the quick editor to see this in action…

This is a good way to deal with more complex key controls. event.which and event.key often won’t cut it, especially with key combos and different systems.

// javascript // keys // tricks // ui
snippet.zone ~ 2021-24 /// {s/z}