1

How would I be able to set this up where the audio stream isn’t hard coded, and where a user would be able to input the stream themselves?

This is something I wanted to do, but haven't figured out how to do it.

Code: https://jsfiddle.net/xnwr5jeq/6/

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

<div class="control">
  <label class="label">Stream</label>
  <input class="input" type="text" />
</div>

Image

Eve Ninnall
  • 1
  • 3
  • 20

1 Answers1

0

First, let's make this a form. Forms are the standard way to encapsulate a collection of input boxes. They're well understood by normal browsers, but also by screen readers and what not.

<form>
  <label>
    Stream
    <input name="url" type="url" />
  </label>
</form>

This is similar to what you had, but I made a few changes:

  • <label> elements need to either wrap what they're labeling, or the they need the for attribute. Otherwise, they're not very useful.
  • I dropped the label class. You can style this in CSS without it by simply using label as the selector.
  • I set a name for the input to make it easier to get its value later.
  • The input is now of type url. This has some built-in validation, and will fall back to a regular text input if the browser doesn't support it.

Your audio element is fine, but let's re-work it a bit:

<audio src=""></audio>

Basically, since we're only getting a single URL from the user, there's no need for child source elements. We also shouldn't set the type because we don't know what it's going to be.

Now, to directly answer your question... we handle the form submit with JavaScript.

// Ensure the page is loaded before querying for elements to attach handlers to
document.addEventListener('DOMContentLoaded', (e) => {
  // Get the form, add a submit handler
  document.querySelector('form').addEventListener('submit', (e) => {
    // Get the form values from the form that was just submitted
    const formData = new FormData(e.target);

    // Set the audio `src` attribute from the form's `url` field input value
    document.querySelector('audio').src = formData.get('url');

    // Prevent default form handling (which would reload the page, in this case)
    e.preventDefault();
  });
});

Fiddle: https://jsfiddle.net/xnwr5jeq/7/

Brad
  • 159,648
  • 54
  • 349
  • 530
  • I think you're missing this: type="submit" value="Set"> Right???? https://jsfiddle.net/xnwr5jeq/16/ – Eve Ninnall Dec 29 '18 at 00:05
  • @MichelleSmith I was just pushing enter, but yes, you could add a submit button if you wanted. – Brad Dec 29 '18 at 00:09
  • How would I be able to get it to work with this code? https://jsfiddle.net/aohz8ns6/20/ – Eve Ninnall Dec 29 '18 at 00:30
  • @MichelleSmith How would you be able to get *what* to work with that code? Post a new question with just the relevant code needed to reproduce the problem you're having. You have a ton of extraneous code in that fiddle that you don't need. – Brad Dec 29 '18 at 00:32