Search code examples
javascriptdom-eventsevent-bubbling

Catching clicks on link (event bubbling)


I'm fairly new to raw JavaScript (used to working with jQuery). I need to catch clicks on a few links, prevent the default action and then do something based on the link href.

Some links are straight up <a href="example.com">Lorem</a>, but others might contain other html elements (images, spans...). I bind the same event handler to all necessary links. I use a workaround function, but in Chrome it uses addEventListener, useCapture is false.

In my event handler, I use event.target.getAttribute('href') to get the location the link is pointing to. This works when working on the first kind of links, but not when I click on an image or span, because event.target is the image or span, not the link. I'm guessing this has something to do with event bubbling, but I'm not quite sure what's the solution.


Solution

  • If you use event delegation (recommended), i.e. bind only one event handler to the document root, then you have to traverse up the DOM from event.target and see whether it is inside an A element:

    var target = event.target;
    
    while (target && target.nodeName !== 'A') {
        target = target.parentNode;
    }
    
    if (target) {
       // click was inside link
    }
    

    If you bind the handler directly to each A element, you can use this instead of event.target to refer to the element the handler is bound to. Read more about this in event handlers.