How can I trigger the same function from multiple events with jQuery?
Often in web development, you need to run the same logic in response to different user interactions—such as a click, keyup, or change event. Here are a few clean ways to achieve that in jQuery.
1. Pass Multiple Event Types to .on()
The simplest approach is to specify multiple events (separated by spaces) in a single .on()
call:
function handleEvent(e) { console.log('Event triggered:', e.type); // Put your common logic here } $('#myElement').on('click keyup', handleEvent);
In this snippet, whenever a click or keyup event fires on #myElement
, the handleEvent
function runs.
2. Chain Event Handlers
Alternatively, you can chain multiple .on()
calls. This approach can be more verbose but offers flexibility if you need separate options (like event data) per event:
function handleEvent(e) { console.log('Event triggered:', e.type); // Your logic here } $('#myElement') .on('click', handleEvent) .on('keyup', handleEvent);
3. Pass an Object to .on()
jQuery also lets you pass an object where keys are event types and values are the functions:
$('#myElement').on({ click: handleEvent, keyup: handleEvent });
This style can be more readable if you have many events and want them all in one place.
Best Practices
- Keep Logic in One Function: Storing your handler in a named function (e.g.,
handleEvent
) avoids code duplication and makes it easy to maintain. - Leverage Event Properties: Within your handler, use
e.type
(orevent.type
) to distinguish which event triggered the function. - Avoid Over-Binding: Consider if you really need multiple events. If the logic differs significantly, you might want separate functions.
Level Up Your JavaScript and jQuery Skills
Creating DRY (Don’t Repeat Yourself) event-handling code is just one aspect of writing clean front-end applications. To deepen your understanding of JavaScript, consider:
-
Grokking JavaScript Fundamentals
A comprehensive look at core JavaScript concepts—from the basics of variable scope to advanced asynchronous patterns. -
Grokking the Coding Interview: Patterns for Coding Questions
Prepare for technical interviews by learning the problem-solving patterns top companies expect you to know.
If you want a real-world interview simulation, check out Coding Mock Interviews at DesignGurus.io, where ex-FAANG engineers provide one-on-one feedback to sharpen your technical skills and communication.
In short, define a single function and bind it to multiple events using .on()
. This method helps keep your code concise, maintainable, and consistent—a key principle for building robust and scalable web applications.