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

Track Mouse and Touch Events

  1. const evts = [
  2.   'touchstart', 'touchmove', 'touchend',
  3.   'mousedown', 'mousemove', 'mouseup', 
  4.   'click', 'mousenter', 'mouseleave'
  5. ]
  6. evts.forEach(type => {
  7.   document.addEventListener(type, e => {
  8.     console.log('event: ', type)
  9.   })
  10. })

See which mouse events are able to fire on the document.

I used this recently when fixing some issues with Android Talkback. Screenreaders will swallow mouse events in some cases.

You can add pointer events too if you need them…

What is the current element? (document.activeElement)

  1. console.log(document.activeElement);

I use document.activeElement constantly when I do accessibility work (getting things to work with screenreaders like NVDA, JAWS or VoiceOver). document.activeElement contains the current element that is in focus on a page.

You can easily debug it with a live expression in the chrome console:

Here is a small demo to play with – try clicking or tabbing around the buttons and inputs:

  1. const el = document.createElement('el');
  2. el.innerHTML = `
  3.   <button class="one">one</button>
  4.   <button class="two">two</button>
  5.   <button class="three">three</button>
  6.   <button class="four">four</button>
  7.   <hr>
  8.   <input type="text" placeholder="type...">
  9.   <hr>
  10.   <input type="range">
  11. `;
  12. document.body.appendChild(el);
  13.  
  14. let lastActive;
  15. setInterval(() => {
  16.   if (document.activeElement != lastActive) {
  17.     lastActive = document.activeElement;
  18.     console.log(lastActive.outerHTML);
  19.   }
  20.  
  21. // no need to update 60fps
  22. }, 100);

Hijack Focus

  1.  
  2. const el = document.body.appendChild(
  3.   document.createElement('div')
  4. );
  5.  
  6. el.innerHTML = `
  7. <button>one</button>
  8. <button>two</button>
  9. <button>three</button>
  10. `;
  11.  
  12. document.addEventListener('click', e => {
  13.   e.target.focus();
  14. });
  15.  
  16. const origFocus = HTMLElement.prototype.focus
  17. HTMLElement.prototype.focus = function() {
  18.   console.log(this.outerHTML, 'focus was called');
  19.   origFocus.call(this);
  20. };
  21.  
  22. el.firstElementChild.focus();

Easy way to debug many calls to focus.

snippet.zone ~ 2021-24 /// {s/z}