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

Easy Random Color

  1.  
  2. document.body.innerHTML += 'click to randomize background color';
  3.  
  4. document.addEventListener('click', () => { 
  5.   const hue = Math.random() * 360;
  6.   document.body.style.background = `hsl(${hue}deg, 50%, 50%)`;
  7. });

One way to generate a random color is to randomize the hue argument of the css hsl. This value is in degrees 0-360 (colorwheel). The other arguments can be randomized as well if you need random saturation and lightness… like this:

  1.  
  2. document.body.innerHTML += 'click to randomize background color';
  3.  
  4. document.addEventListener('click', () => { 
  5.   const hue = Math.random() * 360;
  6.   const saturation = Math.random() * 100;
  7.   const lightness = Math.random() * 100;
  8.   document.body.style.background = `hsl(${hue}deg, ${saturation}%, ${lightness}%)`;
  9. });
// css // dom // graphics // javascript

ClassName Behaviors

  1. const ui = document.body.appendChild(
  2.   document.createElement('div')
  3. );
  4.  
  5. ui.innerHTML = `
  6.   <button class="blue circle redBorder moveDown">click</button>
  7.   <button class="red circle sayHi">click</button>  
  8.   <button class="green circle noBorder moveDown sayHi randomBgColor">click</button>
  9.  
  10.   <style>
  11.     * { -webkit-user-select: none; user-select: none; }
  12.     body, html {
  13.       width: 100%; height: 100%;
  14.     }
  15.     button { 
  16.       position: relative;
  17.       top: 0;
  18.       margin: .5em; 
  19.       cursor: pointer; 
  20.       color: white;
  21.       transition: all 200ms ease-out;
  22.       text-shadow: 1px 2px 1px black;
  23.     }
  24.     .circle {
  25.       width: 50px;
  26.       height: 50px;
  27.       border-radius: 500px;
  28.     }
  29.     .blue {
  30.       background: #275ba1;
  31.     }
  32.     .red {
  33.       background: red;
  34.     }
  35.     .green {
  36.       background: green;
  37.     }
  38.     .redBorder {
  39.       border: 2px solid red;
  40.     }
  41.     .noBorder {
  42.       border: none;
  43.     }
  44.   </style>
  45. `;
  46.  
  47. const actions = {
  48.   moveDown(e) {
  49.     e.target.style.top = `${parseFloat(e.target.style.top || 0) + 30}px`;
  50.   },
  51.   sayHi(e) {
  52.     e.target.innerHTML = [
  53.       'hi', 'hello', 'hey', 'aloha', 'what\'s up'
  54.     ][
  55.       Math.floor(Math.random() * 5)
  56.     ];
  57.     e.target.style.transform = `
  58.       rotate(${Math.random() * 40 - 20}deg) 
  59.       scale(${Math.random() * .3 + 1})`
  60.   },
  61.   randomBgColor(e) {
  62.     const col = `hsl(${Math.random() * 360}deg, 50%, 50%)`
  63.     e.target.style.background = col;
  64.   }
  65. };
  66.  
  67. document.body.addEventListener('click', e => {
  68.   // combine as many actions as we want
  69.   [...e.target.classList].forEach(cls => { 
  70.     const action = actions[cls];
  71.     if (action != null) action(e);
  72.   });
  73. });

This snippet takes the ideas from yesterdays post and goes one level further. This associates behavior with class names, so the class names can be combined to mix and match behavior.

In this case, combining classes like this green circle noBorder moveDown sayHi randomBgColor will cause the element in question to “move down”, “say hi” and randomize its background color when it is clicked. Click the “Try it out” to get a better idea.

// animation // css // dom // events // javascript // tricks // ui

Easy Mouse Events

  1. const ui = document.body.appendChild(
  2.   document.createElement('div')
  3. );
  4.  
  5. ui.innerHTML = `
  6.   <button class="hello">say hello</button>
  7.   <button class="make-box">make a box</button>
  8.   <button class="remove-boxes">remove boxes</button>
  9.   <button class="consoleLog red">log in console</button>
  10.  
  11.   <style>
  12.     button { margin: .5em; cursor: pointer; }
  13.     .red { background: red; color: white; }
  14.     .box {
  15.       position: relative;
  16.       float: left;
  17.       width: 30px;
  18.       height: 30px;
  19.       margin: 1em;
  20.       background: blue;
  21.     }
  22.   </style>
  23. `;
  24.  
  25. const actions = {
  26.   hello(e) {
  27.     alert(e.target.className);
  28.   },
  29.  
  30.   ['make-box']() {
  31.     const box = document.body.appendChild(
  32.       document.createElement('div')
  33.     );
  34.     box.classList.add('box');
  35.   },
  36.  
  37.   ['remove-boxes']() {
  38.     const boxes = [...document.querySelectorAll('.box')];
  39.     const num = boxes.length;
  40.     boxes.forEach((el) => el.parentNode.removeChild(el));
  41.  
  42.    alert(
  43.       num === 0
  44.         ? 'no boxes to remove'
  45.         : `removing ${num} box${num > 1 ? 'es' : ''}`
  46.     );
  47.   },
  48.  
  49.   consoleLog(e) {
  50.     console.log('camelCase instead of kebab-case :D');
  51.   },
  52. };
  53.  
  54. document.addEventListener('mousedown', (e) => {
  55.   const action = actions[e.target.classList[0]];
  56.   if (action != null) action(e);
  57. });

This is a powerful little pattern for managing mouse/touch events. Rather than assigning many listeners, this snippet has one listener on the document. Anytime the page is clicked, we look at the event targets classList and use its first value as a key in an actions object.

I have used this or some variation of it many many times over the years. With a little customization it scales well into large projects. I always find myself on the fence about class naming conventions… kebab-case vs camelCase – probably because it just doesn’t matter that much. For large projects, each main section of the UI will have its own document.addEventListener just for organizational purposes.

Variations

The choice to use the first class as the key for the action is pretty arbitrary. Depending on how you like to set things up you could use the last value of the classList, the element id, the element name, or a custom data attribute etc… Like this:

  1. // id
  2. const action = actions[e.target.id];
  3.  
  4. // name
  5. const action = actions[e.target.name];
  6.  
  7. // data attribute <button data-my-id="test">test</button>
  8. const action = actions[e.target.dataset.myId];
// dom // events // javascript // tricks // ui

Distance Between Two Points (SVG)

  1. const dist = (x1, y1, x2, y2) => 
  2.   Math.sqrt(
  3.     (x1 - x2) ** 2 + 
  4.     (y1 - y2) ** 2);
  5.  
  6. const el = document.body.appendChild(
  7.   document.createElement('div')
  8. );
  9.  
  10. el.innerHTML = `
  11.   <svg style="overflow:visible;">
  12.     <circle id="circA" cx="150" cy="100" r="50" fill="gray" />
  13.     <circle id="circB" cx="150" cy="200" r="50" fill="blue" />
  14.     <text id="text" dy="20" dx="20">move mouse</text>
  15.   </svg>
  16.   <style>
  17.     body, html, svg {
  18.       width: 100%;
  19.       height: 100%;
  20.     }
  21.   </style>
  22. `;
  23.  
  24. function touch(e) {
  25.   const touches = e.touches;
  26.   let x, y;
  27.   if (touches != null && touches.length > 0) {
  28.     x = touches[0].clientX;
  29.     y = touches[0].clientY;
  30.   } else {
  31.     x = e.clientX;
  32.     y = e.clientY;
  33.   }
  34.   return { x, y };
  35. }
  36.  
  37. const hasTouch = navigator.maxTouchPoints > 0;
  38. const move = hasTouch ? 'touchmove' : 'mousemove';
  39. document.addEventListener(move, e => {
  40.   const { x, y } = touch(e);
  41.  
  42.   // using global ids :D
  43.   circB.cx.baseVal.value = x;
  44.   circB.cy.baseVal.value = y;
  45.  
  46.   const distance = dist(
  47.     circA.cx.baseVal.value, 
  48.     circA.cy.baseVal.value, x, y
  49.   );
  50.   text.innerHTML = 'move mouse, distance: ' + distance;
  51.  
  52.   circA.r.baseVal.value = distance - circB.r.baseVal.value;
  53. });

This snippet shows how to calculate the distance between two points. The dist function uses the pythagorean theorem:

  1. const dist = (x1, y1, x2, y2) => 
  2.   Math.sqrt(
  3.     (x1 - x2) ** 2 + 
  4.     (y1 - y2) ** 2);
// dom // graphics // javascript // math // svg

Range Slider and Progress Bar

  1. const NUM = 8;
  2. const NUM_M_1 = NUM - 1;
  3. const ui = document.createElement('div')
  4. ui.innerHTML = `
  5.   <div class="ui">
  6.     <div class="progress" data-ref>
  7.       <div class="progressFill" data-ref></div>
  8.     </div>
  9.     <div class="text" data-ref>
  10.     0% of 100%
  11.     </div>
  12.  
  13.     <div class="dots" data-ref>
  14.     ${
  15.       `<div></div>`.repeat(NUM)
  16.     }
  17.     </div>
  18.  
  19.     <label>
  20.       drag the slider...
  21.       <input class="slider" type="range" min="0" max="100" step="1" value="0" data-ref/>
  22.     </label>
  23.   </div>
  24.   <style>
  25.     body {
  26.       font-family: sans-serif;
  27.     }
  28.     .progress, .dots {
  29.       position: relative;
  30.       width: 80%;
  31.       margin: 0 auto;
  32.       height: 30px;
  33.       border: 1px solid black;
  34.     }
  35.     .progressFill {
  36.       height: 100%;
  37.       width: 0;
  38.       background: red;
  39.     }
  40.     .text {
  41.       padding: 1em;
  42.       background: #ccc;
  43.       margin: .5em;
  44.       font-weight: bold;
  45.     }
  46.     label {
  47.       display: block;
  48.       margin: 1em;
  49.     }
  50.     .slider {
  51.       cursor: pointer;
  52.     }
  53.     .dots {
  54.       border: none;
  55.     }
  56.     .dots div {
  57.       height: 100%;
  58.       width: ${100 / NUM}%;
  59.       float: left;
  60.       transition: background 400ms ease-out;
  61.       background: transparent;
  62.       border-radius: 500px;
  63.       box-shadow: inset 0 0px 0 3px blue;
  64.     }
  65.     .dots div:nth-child(1) {
  66.       background: red;
  67.     }
  68.  
  69.   </style>
  70. `;
  71. document.body.appendChild(ui);
  72.  
  73. // select everything with a `data-ref`
  74. const els = {};
  75. ;[...document.querySelectorAll('[data-ref]')]
  76.   .forEach(el => {
  77.     els[el.classList[0]] = el;
  78.   });
  79.  
  80. function update(e) {
  81.  
  82.   // normal prog bar
  83.   const val = e.target.value;
  84.   els.progressFill.style.width = `${val}%`;
  85.   els.text.innerHTML = `
  86.     ${val}% of 100%
  87.   `;
  88.  
  89.   // segmented dot prog bar
  90.   const idx = Math.floor(val / (100 / NUM));
  91.   if (idx < NUM) { 
  92.     for (let i = 0; i < NUM; i++) {
  93.       els.dots.children[i]
  94.         .style.background = i <= idx ? 'red' : 'white'
  95.     }
  96.   }
  97. }
  98.  
  99. els.slider.addEventListener('input', update);
  100. els.slider.addEventListener('change', update);

Drag slider and watch two progress bars and a text readout update. There are some interesting vanilla tricks in this one.

This trick and a variety of variations on it is pretty powerful:

  1. const els = {};
  2. [...document.querySelectorAll('[data-ref]')].forEach(el => {
  3.   els[el.classList[0]] = el;
  4. });
// css // dom // graphics // javascript // math // strings // tricks // ui
snippet.zone ~ 2021-24 /// {s/z}