Shiny button observer update: ignoring clicks on disabled buttons

In earlier posts, I’ve explained how to add a bit of JavaScript/jQuery code to your project that lets you have one Shiny observeEvent() handler for all your button and anchor clicks. This week I needed disabled buttons, which are easy to do visually by adding the Bootstrap disabled class to the button. But the buttons still responded to being clicked.

To fix this, I made a slight addition to the Shiny click observer, which now looks (in its entirety) like this:

$(document).on('click', 'button,a', function(e) {
   if(e.target.className.indexOf("disabled") >= 0) {
      e.stopPropagation();
      return;
   }
   if(e.target.id.length == 0) { return; }
   if(e.target.nodeName == "A" &&
      typeof e.target.href != "undefined" &&
      e.target.href.length > 0) {
         return;
   }
   Shiny.onInputChange("js.omclick", e.target.id + "_" + (new Date()).getTime());
});

The new code is all in the first if statement, which now looks at the target of each click (ie, the button or link that was clicked on) to see if its list of classes includes disabled. If so, the click event is trashed and nothing happens.

LATER: On the other hand, if you add disabled as an attribute, rather than as a class, the browser itself is likely to take care of both the look and ignoring the click, so this update isn’t really necessary. But it does allow you to use either method.

As a class:
<button id="id" class="disabled">...

As an attribute:
<button id="id" disabled>...

 

Leave a Reply

Your email address will not be published. Required fields are marked *