Charlie
Charlie

Reputation: 11787

Audio tag, add src when clicking on link?

I am attempting to write a page with multiple <audio> tags in it and the page load takes forever (I have around 30 audio clips). A solution I saw was to leave the src="" empty and then dynamically populate when you click on a link...

http://dev.opera.com/articles/view/everything-you-need-to-know-about-html5-video-and-audio/

My snytax is wrong, but it has to do 2 things when the button is clicked. It has to load the video by populating the src and then playing the clip. I thought the following code would work:

document.getElementById('1')[0].src = '1.aif';.play()

Upvotes: 0

Views: 227

Answers (2)

Quentin
Quentin

Reputation: 944441

Your problems are:

  1. getElementById returns the element with the given unique identifier, not a NodeList (so [0] won't work because there isn't a 0 property)
  2. Your second statement is trying to call play on nothing. You need something before the .

You probably want to just set preload="none" instead of trying to dynamically set the src.

Upvotes: 1

pimvdb
pimvdb

Reputation: 154958

Statements are executed separately, so .play() doesn't execute on the element. It's invalid, since a statement cannot start with ..

What you seem to want is "chaining style" (execute several things elegantly in one statement), which jQuery enables you to use:

$("#1").attr("src", "1.aif").play();

Or in pure JavaScript:

var elem = document.getElementById('1'); // returns one element, not an array
elem.src = '1.aif';
elem.play();

Upvotes: 1

Related Questions