fts_acer fts_acer - 1 year ago 39
HTML Question

Button click events intercepted by button content

I have a pretty basic Bootstrap button on my page. I have an event listener listening for clicks on this button. I have an image tag as the content of the button. When a user clicks the button, the event listener fires as desired. However, if the button click lands on the image within the button, the image intercepts the click and the button click event listener doesn't fire. How can I get the button to detect a click on both itself, and its content (e.g. the image tag)?

<button type="button" class="btn btn-custom" id="navLogoButtonRight">
// dev tools indicate clicks land on this <img> and never make
// it to the <button>
<img class="icon" src="img/icon.png">

Note, this is a Twitter Bootstrap button, but I'm not sure that has any bearing on the problem.

Here is the JS, by request.

var navLogoButtonLeft;

function initNav() {
navLogoButtonLeft = document.getElementById('navLogoButtonLeft');

// note, I've tried both 'true' and 'false' here
navLogoButtonLeft.addEventListener('click', handleClick, true);

// this method does fire, but clickEvent is the <img>, not the <button>
function handleClick(clickEvent) {
if(clickEvent.target == navLogoButtonLeft) {
// this line cannot be reached
window.location = './';

window.addEventListener('load', initNav, false);

Answer Source

you could just add the same event listener to the image tag to get the desired effect.

Though you could also go to a more technical level and add a class that sets pointer-events: none; in the CSS and add that class to the end of your img tag