Search code examples
javascriptphpspinner

Loading spinner stays on if middle click link in Chrome


I have a page that uses the spin.js (http://fgnass.github.io/spin.js/#!) pure Javascript spinner to show a spinner when a link (to a slow page) is clicked. I trigger it using onclick on the link.

The problem is in Chrome (v 30.0.1599.69 m) if I middle-button-click on the link to open the slow page in a new tab, then when I return to the original page the spinner is running and keeps running forever. It does not happen in IE or Firefox.

(Obviously if I left-click on the link the spinner will die when the new page is loaded.)

My link looks like this: <a href="other-sources.php?id='.$id.'" onClick="return spinner(40);">Other Sources</a>

And the script that starts the spinner looks like this:

 <script type="text/javascript">
// Display spinner while waiting for Other Sources to display.
// Parameter is vertical position of spinner, since we have 2 Show Source links
function spinner(posn) {
    var opts = {
        lines: 15, // The number of lines to draw
        length: 7, // The length of each line
        width: 4, // The line thickness
        radius: 15, // The radius of the inner circle
        corners: 1, // Corner roundness (0..1)
        rotate: 0, // The rotation offset
        color: '#000', // #rgb or #rrggbb
        speed: 1, // Rounds per second
        trail: 60, // Afterglow percentage
        shadow: false, // Whether to render a shadow
        hwaccel: false, // Whether to use hardware acceleration
        className: 'spinner', // The CSS class to assign to the spinner
        zIndex: 2e9, // The z-index (defaults to 2000000000)
        top: posn, // Top position relative to parent in px
        left: 850 // Left position relative to parent in px
    };
    var target = document.getElementById('main');
    var spinner = new Spinner(opts).spin(target);
return true; 
}
</script>

To complete the picture, I have this in the Head section:

<script src="spin.min.js"></script>

Is there something I can put in the javascript to make it ignore middle button clicks? I read elsewhere that detecting the buttons is rather quirky.

Hmmm. I see there is a bug report about it dating back to 2008: https://code.google.com/p/chromium/issues/detail?id=1687


Solution

  • Ok, I solved the problem as follows:

    1. Changed the link from onClick to onmouseup

    2. Added the following code to the start of the javascript:

      if (event.which == null)
         /* IE case */
         var button= (event.button < 2) ? "LEFT" :
                   ((event.button == 4) ? "MIDDLE" : "RIGHT");
      else
         /* All others */
         var button= (event.which < 2) ? "LEFT" :
                   ((event.which == 2) ? "MIDDLE" : "RIGHT");
         if (button != "LEFT")
                return true;