Missing click event for <span> inside <button> element on firefox

25,084

Solution 1

As far as i known clicking the children elements won't work because it is nested inside a button. A button is not container for child elements - only for text.

If you try like below it always tell that you clicked the button.

<button type="button" onclick="alert('You clicked the button!');">
   inside a button <span onClick="alert('clicked span');">**Not working**</span>
</button>

So, my suggestion is to use another span or a div

<div class="button_replace">
  inside a div <span onClick="alert('clicked span');">**working**</span>
</div>

Hope it helps...

Note: Your code will work in chrome but not in firefox and my answer is alternative solution for making work in firefox

Solution 2

You have to add the pointer-events property to the span element.

button span {
  pointer-events: none;
}

Solution 3

Add a pointer-event to your button in css like:

button span {
    pointer-events: none;
}

Clicks on the button element will be ignored

Solution 4

Working
inside a button Not working

What you actually want to do here is have a click event on the button - always the button, as that is the native HTML element and has built in accessibility for all.

The reason your button click won't fire if you click on something wrapped in a span (or or etc) inside a button is because you are listening for a click on event.target (what's actually clicked) and not on event.currentTarget.

If you want to listen to the button click itself (a click anywhere inside the button, including the span) you would use something like this:

HTML:

<button type="button" class="jsAlertOnClick">
  Inside a button 
  <span onClick="alert('Span Clicked, and...');">I'm in a span</span>
</button>

Javascript:

const myButton = document.querySelector('.jsAlertOnClick');

function handleBtnClick(event) {
  const btn = event.currentTarget;
  window.alert(btn + 'has been clicked!');
}

myButton.addEventListener('click', handleBtnClick);

If you click on the span, that alert will fire first, followed by the button one. If you click elsewhere in the button, only that alert will fire.

Share:
25,084
Admin
Author by

Admin

Updated on March 07, 2020

Comments

  • Admin
    Admin about 4 years

    I am experiencing problem with Firefox 32 when I bind action on click event of span element inside a button element. Other browsers seems to works well.

    Here the code illustrating the issue on jsFiddle.

    <span onClick="alert('test');">**Working**</span><br>
    <button>inside a button <span onClick="alert('test');">**Not working**</span></button>

    Does anybody know why and if it's a bug or a feature ?