app.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536
  1. /* global jQuery */
  2. /**
  3. * Tiny site-wide script. One purpose today: turn any element carrying a
  4. * `data-href` attribute into a clickable row / button without needing an
  5. * inline onclick (which would force `'unsafe-inline'` in the CSP).
  6. *
  7. * Middle-click / Ctrl+click / Cmd+click open in a new tab, matching
  8. * native anchor-link behaviour.
  9. */
  10. (function ($) {
  11. 'use strict';
  12. $(document).on('click', '[data-href]', function (ev) {
  13. // Ignore clicks that originated on an interactive descendant.
  14. if ($(ev.target).closest('a, button, input, select, textarea, label').length > 0) {
  15. return;
  16. }
  17. const href = String($(this).attr('data-href') || '');
  18. if (href === '') { return; }
  19. if (ev.metaKey || ev.ctrlKey || ev.button === 1) {
  20. window.open(href, '_blank');
  21. } else {
  22. window.location.href = href;
  23. }
  24. });
  25. // Make the row visibly clickable via keyboard + screen-readers.
  26. $('[data-href]').attr('role', 'link').attr('tabindex', '0');
  27. $(document).on('keydown', '[data-href]', function (ev) {
  28. if (ev.key === 'Enter') {
  29. ev.preventDefault();
  30. window.location.href = String($(this).attr('data-href') || '');
  31. }
  32. });
  33. })(jQuery);