0

I have the following scenario..

When the user visit my website I show the user some audio files from the server. When the user clicks on one link, then the jquery function is eventually executed and change the source of the embedded object to selected file.

my script is :

<script type="text/javascript">
    $("#song").click(function(){
        var src=$(this).attr("href");
        var plyr=document.getElementById("mplayer");
        var clone=plyr.cloneNode(true);
        clone.setAttribute('src',src);
        plyr.parentNode.replaceChild(clone,plyr)
    });
</script>

Link to select audio file.

  <a href="resources/songs/xx21.mp3" id="song">

xx21

And the object is

<div id="music">
    <embed type="audio/mpeg" src="#" name="plugin" height="100%" width="100%" id="mplayer">
</div>

What happening for me is, When I click on the link. The song plays in new page. I need to play the song with embedded object inside the div music.

2 Answers 2

1

If you have more than one link that will load a song, use a class instead of an id, as each id is supposed to be unique on the page. Then you can do this to change the src of the embed to the href of the link that is clicked:

$('.song').on('click', function(e) {
    $('#mplayer').attr('src', $(this).attr('href'));
    e.preventDefault();
});

e.preventDefault() will prevent your browser from trying to go to the location of the file.

Sign up to request clarification or add additional context in comments.

3 Comments

It is not working for me. When I click on a link, song will play in new page(Refreshing the page and changing the address tohttp://localhost:8080/skypark/sp/resources/songs/xx21.mp3).I have more than one link for different songs.
You need to change it from id="song" to class="song", as you should only use each id once per page.
Yes I changed id="song" to class="song"
0

You need to prevent the default execution of the element. Default execution of a link is - open the link.

What you can do:

Either <a href="link-to-sound" onClick="return false;"> or

<script type="text/javascript">
$(".song").click(function(event){
event.preventDefault();
var src=$(this).attr("href");
var plyr=document.getElementById("mplayer");
var clone=plyr.cloneNode(true);
clone.setAttribute('src',src);
plyr.parentNode.replaceChild(clone,plyr)
});
</script>

you need to add event.preventDefault()

1 Comment

It is not working for me. When I click on a link, song will play in new page(Refreshing the page and changing the address tolocalhost:8080/skypark/sp/resources/songs/xx21.mp3).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.