DEV Community

Cover image for Event Listeners and Anchor Tag
Vijay Pagare
Vijay Pagare

Posted on

Event Listeners and Anchor Tag

Question:

When does the anchor tag redirection happen given that multiple event listeners are attached to it?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Event listeners and Anchor tag</title>
</head>
<body>
    <a id="demo" onclick="inlineHandler(event)" href="https://www.google.com">link demo</a>
</body>

<script>
    const inlineHandler = (e) => {
        console.log('inline Handler');
        setTimeout(()=> {
            console.log('This will not get executed as redirection would have been occurred by then.');
        }, 1000);
    }

    const link = document.getElementById('demo');

    link.addEventListener('click', (e) => {
        console.log('event listener 1');
    })

    link.addEventListener('click', (e) => {
        console.log('event listener 2');
        // e.preventDefault();
    })

    link.addEventListener('click', (e) => {
        console.log('event listener 3');
    })
</script>

</html>
Enter fullscreen mode Exit fullscreen mode

Output of the code when multiple event listeners are attached to an anchor tag

Learnings

  • Inline handler always gets executed first.
  • Event listeners (for the same element) are handled in the order they are written.
  • Anchor tag redirection happens after the execution of all event listeners.
  • If any of the event listener triggers preventDefault (irrespective of the order) then redirection won't happen.

Use case: Trigger analytics event on anchor tag link click.

I'll leave the guesswork for async code upto you. For any doubts or discussions, please feel free to comment. Thanks!

Top comments (0)