0

I wrote a simple script to add a floating button to a series of pages that redirects to a URL depending on some features. This is added via Tampermonkey.

The following produces a button in both Chrome and Firefox but it is only clickable in Chrome:

var html = '<div id="gmSomeID"><button id="tapButton" type="submit"><a href="'+output_url+'" style="color:white">A</a></button></div>';
    $("body").append(html);

Any ideas what may be driving the issue?

Brock Adams
  • 90,639
  • 22
  • 233
  • 295
NickP
  • 1,354
  • 1
  • 21
  • 51

1 Answers1

4

That code is semantically ambiguous and invalid HTML; don't code that way!

Consider:

var output_url = '#';
var newHtml = `
    <div>
        <button id="badButton" type="submit">
            <a id="badLink" href="${output_url}">Click me</a>
        </button>
    </div>
`;
$("body").prepend (newHtml);
$("#badButton, #badLink").click ( zEvent => {
    console.log ("Clicked: ", zEvent.target.id);
} );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

What do you expect would happen?

  • The button code tells the browser to execute any event handlers on the button and then submit the containing form. If there was such a form, submitting it would would normally navigate the page away from its current instance -- blocking the link from executing.
  • The link code would navigate away, blocking the button from executing.

If you run that code and click, then currently you get:

  • On Chromium based browsers: Clicked: badLink.
  • On Firefox: Clicked: badButton.

Because it's invalid HTML, browsers are not guaranteed to handle it in a uniform way.

So:

  1. Do not put hyperlinks inside buttons.
  2. If you want the HTML to navigate to another page, use a link, not a button. You can use CSS to make it look like button.
  3. If you want the HTML to change the state of the page or to submit or reset a form, use a button.
  4. Do not use type="submit" unless the button is inside a form and really meant to submit it. Always specify type="button" by default, to avoid unexpected behavior.
Brock Adams
  • 90,639
  • 22
  • 233
  • 295