Call two functions from the same onclick
To call multiple functions on a single click, chain them using semicolons:
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:
Mastering Event Handling with addEventListener()
For more complex scenarios or when a clean code structure is essential, replace inline handlers with addEventListener()
:
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:
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
:
Catching Errors: The Safety Net
Nothing interrupts a performance like an error. Including try-catch
blocks can help maintain a smooth flow:
Decoupling with Event Listeners: Separate Yet Together
Separate your HTML from JavaScript to fortify both readability and accessibility:
By unscrambling JavaScript from HTML, you're not just respecting the separation of concerns but also making your code SEO friendly.
Was this article helpful?