James
James

Reputation: 2984

how to change object embed source via jquery

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.

Upvotes: 0

Views: 1628

Answers (2)

mr.VVoo
mr.VVoo

Reputation: 2270

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()

Upvotes: 0

Matt Cain
Matt Cain

Reputation: 5768

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.

Upvotes: 1

Related Questions