Lander
Lander

Reputation: 3437

What is the "correct" behavior for elements inside of a <button>?

I was trying to fix a bug where a file input inside of a button element was not working properly on Firefox/IE. The <input> was being made extremely large with its opacity set to 0 which allowed whoever wrote the markup to create a custom-styled "Browse" button.

This worked just fine in Chrome, Safari, and Opera (which all happen to be running Webkit/Blink). Clicking on the button would transparently click on the "Browse..." button from the nested <input>, but Firefox and IE had different behaviors. I fixed this issue by just making the input hidden and not a child of the button, then calling its click event when the button is clicked.

This had me curious though and I put together some tests to see what works and what doesn't: JSFiddle.

(If the fiddle ever happens to go away, here are the contents:

HTML:

<button>
    <label for="checkbox-input">Click me</label>
    <input id="checkbox-input" type="checkbox"/>
</button>

<button>
    <input type="text"/>
</button>

<button>
    <input type="color"/>
</button>

<button>
    <a href="#test">test</a>
</button>
<button>
    <span id="clicky">testing!</span>
</button>
<button>
    <span class="crosshair">testing!</span>
</button>

CSS:

.hidden {
    opacity: 100;
}

button {
    cursor: pointer;
}

.crosshair {
    cursor: crosshair;
}

JS:

$('#clicky').on('click', function() {
    alert('clicky');
});

It seems as though in Chrome, Safari, and Opera, all click through the button and trigger the click event on both the button and nested element. Firefox only clicks the button. IE only clicks the button, but displays the cursor when hovering over the nested element.

Allowed content for a button according to the spec:

Phrasing content, but there must be no interactive content descendant.

The input element falls under both phrasing and interactive content. Based off of this information, do any of these browsers display correct behavior?

Upvotes: 3

Views: 111

Answers (1)

Nisse Engstr&#246;m
Nisse Engstr&#246;m

Reputation: 4752

You can't have an INPUT element inside a BUTTON. Your HTML is broken. There is no way to determine if any of the browsers behave correctly or not.

Upvotes: 1

Related Questions