Explain Codes LogoExplain Codes Logo

Call two functions from the same onclick

javascript
event-handling
best-practices
async-functions
Nikita BarsukovbyNikita Barsukov·Dec 4, 2024
TLDR

To call multiple functions on a single click, chain them using semicolons:

<button onclick="firstAction(); secondAction();">Click me</button>

In this snippet, the functions firstAction and secondAction are triggered sequentially on click, realizing a quick solution with minimal code.

Taming the Beast: Handling Return Statements

While chaining functions makes your code sleek and efficient, be wary of early return statements as they tend to interrupt function execution:

function firstAction() { if (foo) return; // Watch out! This return could halt secondAction! } function secondAction() { /* Whatever you do... */ }

Mastering Event Handling with addEventListener()

For more complex scenarios or when a clean code structure is essential, replace inline handlers with addEventListener():

document.getElementById('myButton').addEventListener('click', function() { firstAction(); // Act 1. secondAction(); // Act 2. Let the drama unfold! });

This way, you strengthen the code's maintainability without compromising on modern web development best practices.

Ensuring Function Execution: The Wrapper Function Technique

A well-designed wrapper function can keep the chain of executions from breaking, if function calls are wrapped inside a try-finally block:

function handleOnClick() { try { firstAction(); // Do or do not, there is no try. But there is a finally... } finally { secondAction(); // ...so I’ll always be there. } }

The secondAction will run no matter what happens in firstAction, thanks to the protective cocoon of the try-finally block.

Assuring Reliable Function Execution

Async Functions: The Promise of Harmony

Async functions can disturb the symmetry of execution. Fortunately, you can bring order to the chaos with Promises or async/await:

async function conductorCall() { await firstSymphony(); // Wait for me! await secondSymphony(); // Your turn, mate! }

Catching Errors: The Safety Net

Nothing interrupts a performance like an error. Including try-catch blocks can help maintain a smooth flow:

function conductorCall() { try { firstSymphony(); } catch(error) { console.error('First Symphony had a false note:', error); } try { secondSymphony(); } catch(error) { console.error('Second Symphony went off-key:', error); } }

Decoupling with Event Listeners: Separate Yet Together

Separate your HTML from JavaScript to fortify both readability and accessibility:

const button = document.getElementById('playButton'); button.addEventListener('click', conductorCall);

By unscrambling JavaScript from HTML, you're not just respecting the separation of concerns but also making your code SEO friendly.