lavekyl
lavekyl

Reputation: 23

Direct click of div won't play audio/video. Click below div and it plays

I am building a WordPress site and found some examples for audio/video elements playing upon clicking another element with a data-value. Here is where I took the code from that I used for this particular situation: change <audio> src with javascript.

See my code below:

/* Load music to music player on single band page */
function musicPlay(e){
  e.preventDefault();

  var elm = e.target;
  var audio = document.getElementById('audio');

  var source = document.getElementById('audioSource');
  source.src = elm.getAttribute('data-value');

  audio.load();
  audio.play();
}

And here is the code where the audio will be loaded:

<div class="media-widget">
  <audio id="audio" controls="controls">
    <source id="audioSource"></source>
      Your browser does not support the audio format.
  </audio>
  <div id="musicList">
    <div class="media-info" onclick="musicPlay(event)" data-value="cool-song.mp3">
      <div class="media-number">
        1.
      </div>
      <div class="media-title">
        Cool Song
      </div>
      <div class="media-length">
        4:31
      </div>
    </div>
    <!-- /.media-title -->
  </div>
  <!-- /#musicList -->
</div>
<!-- /.media-widget -->

I am building this out in WordPress and using Advanced Custom Fields to loop through songs. You can check out the link here to test it: http://184.154.22.154/~pacif099/band/hillcrest-court/ and see what I am talking about when clicking one of the songs. Click directly on the song and it won't load, but if you click just below the song it loads and starts playing.

UPDATE:

I also get this error in the console:

Uncaught (in promise) DOMException: The play() request was interrupted by a new load request.

Upvotes: 0

Views: 219

Answers (1)

lavekyl
lavekyl

Reputation: 23

I resolved my own issue. For reasons that I am unable to explain, the use of multiple div elements within the media-info div created issues. So updated it to this:

<ul id="musicList">
  <li>
    <div class="media-info">
      <div class="media-number">
        <p>1.</p>
      </div>
      <div>
        <a href="#" class="media-title" data-value="cool-song.mp3">
          Cool Song
        </a>
      </div>
      <div class="media-length">
        <p>4:31</p>
      </div>
    </div>
    <!-- /.media-info -->
  </li>
</ul>
<!-- /#musicList -->

And I updated the JavaScript to match the code I used from this other question: change <audio> src with javascript.

/* Load music to music player on single band page */
musicList.onclick = function(e) {
  e.preventDefault();

  var elm = e.target;
  var audio = document.getElementById('audio');

  var source = document.getElementById('audioSource');
  source.src = elm.getAttribute('data-value');

  audio.load();
  audio.play();
}

Upvotes: 0

Related Questions