I have created an DOM element for an MDC slider (https://material.io/develop/web/components/sliders).
It looks nice (except for the colors). And it works, but I really have no idea how to initialize it.
I import MDC from the CDN. I can't understand from the documentation how to do the initialization. This is one version that works:
setTimeout(() => { slider = new mdc.slider.MDCSlider(eltSlider) });
Without setTimeout
it does not work.
I have tried using a Promise instead and wait a second. That does not work.
And maybe even worse: If I use a Promise to wait after the setTimeout it does not work any more.
What is going on and how am I supposed to do it?
I do not use ts. And I do not use any package handler. Just plain JavaScript. (And I would be glad if the documentation covered this use case first.)
(There seems to be only one other question about MDCSlider here. It does not cover my question: actual use of foundation and adapter class of mdc-components)
EDIT: By "import from CDN" I mean the setup mentioned here: https://material.io/develop/web/docs/getting-started
<link href="https://unpkg.com/material-components-web@latest/dist/material-components-web.min.css" rel="stylesheet">
<script src="https://unpkg.com/material-components-web@latest/dist/material-components-web.min.js"></script>
There is no JavaScript error. It is just the slider on the screen that does not work. (It looks ok, but it does not work.)
I think this is a problem with MDC and the DOM state. The example in the link above suggests that the DOM is ready, but it does not say so. And it does not explain how to check this when manipulating the DOM with JavaScript.
it seems the latest
version on unpkg was recently changed from 8.0.0
to 9.0.0
fixing this issue
<script src="https://unpkg.com/material-components-web@9.0.0/dist/material-components-web.js"></script>
<link href="https://unpkg.com/material-components-web@9.0.0/dist/material-components-web.css" rel="stylesheet">
<div class="mdc-slider">
<input class="mdc-slider__input" type="range" min="0" max="100" value="50" name="volume" aria-label="Continuous slider demo">
<div class="mdc-slider__track">
<div class="mdc-slider__track--inactive"></div>
<div class="mdc-slider__track--active">
<div class="mdc-slider__track--active_fill"></div>
</div>
</div>
<div class="mdc-slider__thumb">
<div class="mdc-slider__thumb-knob"></div>
</div>
</div>
<script>
sldr = new mdc.slider.MDCSlider(document.querySelector('.mdc-slider'));
sldr.root.addEventListener('MDCSlider:change', (e)=>console.log(e));
</script>
now works as expected https://stackblitz.com/edit/js-4ycwx5?file=index.html