How to apply MDC web javascript (like MDCRipple) to content that has been loaded in with AJAX

1.3k Views Asked by At

Im currently making a web app that uses AJAX to change the content inside the page, but I'm running into an issue with getting the javascript to apply to elements that have been loaded in rather than starting on the page.

For example, if I had a button in my starting HTML that called an AJAX function,

<button onclick="AjaxFunction()">Change Button</button>

That got this MDC button from a separate page,

<button class="mdc-button">New Button<button>

Then if I had this in my app.js file,

import {MDCRipple} from '@material/ripple';

const buttonRipple = new MDCRipple(document.querySelector('.mdc-button'));

Then when I click on the original button to get the new button into the page, the ripple wont apply because the New Button didn't start on the page to begin with.

How would I get the ripple to initialise on the New Button after it is added to the page?


This then kind of leads into my second question, and that would be, if it is possible to initialise the ripple on the New Button through AJAX, how would I then get to it adapt to work on any new MDC content that is added through AJAX whether it just MDC buttons, or doesn't have any buttons at all but has other MDC content that needs Javascript to function. Like a drawer or text field.

1

There are 1 best solutions below

2
On BEST ANSWER

I suppose you are creating your button element inside the callback of your AjaxFunction something like this:

var button = document.createElement("button");
button.className = 'mdc-button';
button.innerText = 'New Button';
document.body.append(button);

You can simply add the ripple effect by adding the following code:

new MDCRipple(button);

Now to automatically initialize all components you can use the package mdc-auto-init. Running the initialize code multiple times is no problem as stated here.

Edit: the mdc variable is not set when you use a bundler like webpack. If you want all be able to get the same mdc variable you can see this answer or create it yourself:

window.mdc = {autoInit: mdcAutoInit, ...};