userknowmore
userknowmore

Reputation: 137

How to change audio src by click using jquery?

How to change dynamically audio src using jquery?

  <audio id="audio" controls="" >
    <source src="" type="audio/mpeg" />
    </audio>

<ul id="playlist">
  <?php if($lists) { foreach ($lists as $list) { ?>
    <li class="active">
      <a href="music/<?php  echo $list;  ?>.mp3">
         <?php  echo $list;  ?> </a>
    </li>   
  <?php }}?>
</ul>

Upvotes: 1

Views: 3580

Answers (3)

TheOnlyError
TheOnlyError

Reputation: 1451

Use the jQuery .attr() tag, check it out here.

More information about this tag here.

  $("#audio").attr("src", "new src here");

Upvotes: 1

Saumil
Saumil

Reputation: 2517

You can give an id attribute to src of the source you want to change as,

<source src="" type="audio/mpeg" id="mySrc"/>

Now through jQuery,

$("#mySrc").attr("src","Your-Value");

Suppose you want to change the src value when a button is clicked, you can write,

$(document).ready(function(){
    $("#myBtn").click(function(){
        $("#mySrc").attr("src","Your-Value");
    });
});

Here is a demo

Upvotes: 2

dfsq
dfsq

Reputation: 193261

You will need to bind click event handler to a (or delegate events to parent #playlist) and assign new src to #audio source:

$('#playlist').on('click', 'a', function(e) {
    e.preventDefault();
    var src = $(this).attr('href');
    $('#audio source').attr('src', src);
});

Important: remember to prevent default behavior of HTMLAnchorElement on click which is page reload.

Upvotes: 1

Related Questions