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.
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.targetand see whether it is inside anAelement:If you bind the handler directly to each
Aelement, you can usethisinstead ofevent.targetto refer to the element the handler is bound to. Read more aboutthisin event handlers.