Search code examples
jquerymaterial-designmaterial-components-web

Detecting if Material Design Button is clicked


I am trying to run some code when a Material Design Button component is clicked. Nothing seems to be working... can you help? I have tried the following:

  1. using an onclick when the button is selected, but this doesn't appear to trigger
  2. Using Jquery to detect the click - but again this doesn't appear to work.

How do we get buttons to trigger functions( surprisingly this is not listed in the documentation!)

<!-- Adding button to add new items-->
          <button class="mdc-fab mdc-fab--extended" id="addItem" onClick="addItem">
            <div class="mdc-fab__ripple"></div>
            <span class="material-icons mdc-fab__icon">add</span>
            <span class="mdc-fab__label">New Task</span>
          </button>
          <!-- End Button -->

Solution

  • Had the same issue.
    In the end I used jquery to add an event listener on all items with a specific class.

    for(item of data) {
      template = `
         <button pizza-id="${item.pizzaName}" class="order-btn mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--accent">
            Order
          </button>
                 `
      // Dynamic rendering of the buttons
      $("#root-menu").append(template)
    }
    // Adding click event listeners on all generated buttons with the class "order-btn"
    $(".order-btn").click(orderPizza);
    

    Now clicking the button works as expected and calls a function called orderPizza with the event as parameter !

    I think that the classic onClick attribute doesn't work because the click doesn't really occur on the button itself but rather on the autogenerated <span> inside it.