← Todos los ejemplos

JavaScript Navegación reddit.com

Reddit: saltar entre posts con las teclas J y K

Añade los atajos J y K que desplazan suavemente el feed al post siguiente o anterior.

Código para copiar

// Jump between feed posts with the J and K keys
function posts() {
  return Array.prototype.slice.call(document.querySelectorAll('shreddit-post'));
}
function current(list) {
  return list.findIndex(function (p) {
    const r = p.getBoundingClientRect();
    return r.top >= -2 && r.top < window.innerHeight / 2;
  });
}
document.addEventListener('keydown', function (e) {
  if (e.ctrlKey || e.metaKey || e.altKey) { return; }
  const tag = (e.target.tagName || '').toLowerCase();
  if (tag === 'input' || tag === 'textarea' || e.target.isContentEditable) { return; }
  if (e.key !== 'j' && e.key !== 'k') { return; }
  const list = posts();
  if (!list.length) { return; }
  let i = current(list);
  if (i < 0) { i = 0; }
  i += (e.key === 'j' ? 1 : -1);
  i = Math.max(0, Math.min(list.length - 1, i));
  list[i].scrollIntoView({ behavior: 'smooth', block: 'start' });
});

Cómo usar este ejemplo

  1. Copia el código con el botón de arriba.
  2. Instala JustZix (2 minutos) y abre la extensión en la página de destino.
  3. Añade una nueva regla que coincida con esa página.
  4. Pega el código en el panel JavaScript de la regla y guarda — se ejecuta en cada visita a la página.

Valora este ejemplo

Sin valoraciones — sé el primero.

¿Funciona este ejemplo?

Los snippets son inútiles sin un lugar donde pegarlos.

JustZix se instala en 2 minutos y ejecuta tu código en cada página coincidente. Sin cuenta, sin pago.

Descargar gratis Ver casos de uso