Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

108
Vistas
Replace multiple click handlers with a single click handler

I'm wondering if it's possible to clean up these click events a bit:

$(document)
    .on('click', '.newGameItem', getNewGameItem)
    .on('click', '.startGame', startThisGame)
    .on('click', '.showThisGameInfo', showThisGameInfo)
    .on('click', '.closeThisGameInfo', closeThisGameInfo)
    .on('click', '#api_game_test', testApiGame)
    .on('click', '.nextGame', shiftGames)
    .on('click', '.confirm_cancel', cancelLexTimer)
    .on('click', '.completed_submission', reload)
    .on('turbolinks:load', function() { ... });

The first 8 methods in the chain are click events—is there a way in javascript to combine these under one click "umbrella" even though the click events are delegated to different elements

about 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

You could use a single .click and check the target of the click with the event argument:

$(document).on('click', function (event) {
  var target = event.target;

  if ($(target).hasClass('newGameItem')) getNewGameItem();
  if ($(target).hasClass('startGame')) startThisGame();

  if (target.id == 'api_game_test') testApiGame();

  // etc
})

Here is the doc (quite poor) about jQuery's event.target: api.jquery.com/event.target

about 4 years ago · Santiago Trujillo Denunciar

0

You're not going to get away from a big block of something, be it .on or GG's answer. You could always put it in a separate .js file to separate it so it's not cluttering up your code.

// in addHandlers.js
function addHandlers(document) {
    document.on('click',...
}

This will clean up your code while getting all of that non-essential clutter out of the way while you're doing the fun stuff.

about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda