Material Design ripple only appearing on first HTML element

400 Views Asked by At

I'm trying to implement Material Design FABs on the web with the ripple effect.

I have the following dummy HTML:

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="bundle.css">
    </head>
    <body>
        <button class="mdc-fab" id="first" aria-label="First">
            <div class="mdc-fab__ripple"></div>
        </button>
        <button class="mdc-fab" id="second" aria-label="Second">
            <div class="mdc-fab__ripple"></div>
        </button>
        <button class="mdc-fab" id="third" aria-label="Third">
            <div class="mdc-fab__ripple"></div>
        </button>
        <script src="bundle.js" async></script>
    </body>
</html>

Here is the SCSS:

@use "@material/fab/mdc-fab";
@use "@material/fab";

And here is the JS:

import {MDCRipple} from '@material/ripple';
const fabRipple = new MDCRipple(document.querySelector('.mdc-fab'));

I've got the ripple effect to show properly on the first button when clicked, but, for some reason, the ripple does not appear for any of the buttons that follow.

In other words, it seems the ripple effect is only working for the first element but not the ones after it. Does anyone know what I'm doing wrong?

2

There are 2 best solutions below

0
On BEST ANSWER

Got it! I guess it helps to read the documentation as well. ‍♂️

const fabRipple = [].map.call(document.querySelectorAll('.mdc-fab'), function(el) {
    return new MDCRipple(el);
});
0
On

Docs for document.querySelector:

The Document method querySelector() returns the first Element within the document that matches the specified selector, or group of selectors. If no matches are found, null is returned.

If you want to select multiple elements, use document.querySelectorAll instead.

But the MDCRipple constructor only seems to accept a single element. Hence, you could use a loop or map to activate them all:

// Transform the NodeList to an Array using the ES6 spread syntax (...)
const buttons = [...document.querySelectorAll('.mdc-fab')]; 
const fabRipples = buttons.map(btn => new MDCRipple(btn)); // An Array of Ripple objects