Get element id from a dmx repeat into javascript

The dynamic bindings get updated in a later step, after the component is initialized. The component must have a static id to register itself with. You can also add a dynamic id, but this will only update the id of the dom element and not the name of the component. That means that you can access a component with an expression only by his static name, but you can use the dynamic id for accessing it in the dom.

Example:

<video id="video" dmx-bind:id="'video' + $index">

You can access it using an expression with {{video.play()}}. In the DOM you can access it with document.getElementById('video0').play().

When elements are in a repeater, it is very difficult to access them from outside the repeater. So easiest is probably to use the DOM method.

So having a look at the code from your first post and changing the javascript to make it work:

<div class="row" is="dmx-repeat" id="repeat2" dmx-bind:repeat="pagedItemsList.data.Paged_Items.data" key="itemlist">
  <div class="player-container">
    <audio dmx-bind:src="Description_Audio_file" onended="ended(this)"></audio>
    <button class="play" onclick="play(this)">Play</button>
  </div>
</div>
<script>
  function play(btn) {
    var audio = btn.parentElement.querySelector('audio');
    if (audio.paused) {
      audio.play();
      btn.className = 'pause';
    } else {
      audio.pause();
      btn.className = 'play';
    }
  }

  function ended(audio) {
    var btn = audio.parentElement.querySelector('button.pause');
    if (btn) btn.className = 'play';
  }
</script>

I could use dynamic ids, but that would make it actually more complex. A nice trick, that I also didn’t know would work, is to use dmx-bind with events. Like:

dmx-bind:onclick="play({{$index}})"

This is a different syntax then dmx-on:click which can only use expressions and call methods from components, with dmx-bind you are able to call javascript functions with dynamic data.

Thank you Patrick for the excellent explanation, this gives me somewhere to work towards, much appreciated.

Thanks, Patrick, for this valuable input, it works indeed! :wink: :grinning: