JavaScript: Events
Illustration by John Hersey

Playing media events


From:

JavaScript: Events

with Ray Villalobos

Video: Playing media events

So far we've been working with events and dom elements that are pretty closely related to each other. So for example images, and maybe if you clicked the image you'd get a larger version of the image, those things are pretty closely related. So in the next series of movies, I'm going to be showing you how to build an audio jukebox. This is a type of project that has different kinds of events and elements, so. You'll be clicking on a list item, and that's actually going to generate an audio object. Now media elements are super easy to do with HTML5. All you really have to do to play a sound on your page is just create an audio element with a source and maybe some controls.

Start your free trial now, and begin learning software, business and creative skills—anytime, anywhere—with video instruction from recognized industry experts.

Start Your Free Trial Now
please wait ...
Watch the Online Video Course JavaScript: Events
2h 10m Intermediate Sep 17, 2013

Viewers: in countries Watching now:

Learn about the different types of JavaScript events available to use in your applications, including traditional events like mouse, form, and window events, plus events that allow you to manage the DOM and HTML5 events that deal with media. Author Ray Villalobos shows how to propagate and register events during the capturing and bubbling phases, cancel an event or default behavior, and respond to clicks, mouse-overs, right-clicks, following the mouse, and loading images. Plus, Ray demos an audio jukebox project and a drag-and-drop game that shows JavaScript desktop and touch events in action.

Topics include:
  • Understanding event registration and propagation
  • Analyzing event properties
  • Creating and removing DOM elements with events
  • Removing an event
  • Canceling and preventing default events
  • Playing media events
  • Handling media pauses
  • Dragging and dropping
  • Adding touch events
Subjects:
Developer Web
Software:
JavaScript
Author:
Ray Villalobos

Playing media events

So far we've been working with events and dom elements that are pretty closely related to each other. So for example images, and maybe if you clicked the image you'd get a larger version of the image, those things are pretty closely related. So in the next series of movies, I'm going to be showing you how to build an audio jukebox. This is a type of project that has different kinds of events and elements, so. You'll be clicking on a list item, and that's actually going to generate an audio object. Now media elements are super easy to do with HTML5. All you really have to do to play a sound on your page is just create an audio element with a source and maybe some controls.

Now every one of those elements has a Javascript counterpart, and what's even cooler is there are methods that will generate media events, like for example, playing a song. And then there's also methods that will be created when a song finishes playing. If you want to dig into the code for audio and media and javascript, make sure you check out this page. You can see that there's a lot of methods and properties that you can use when working with media. So let's take a look at our HTML file. It's pretty simple. It's just a basic HTML page called a stylesheet as well as a JS file, and it has a series of list items in an unordered list with- Player.

The interesting thing here is that we have added a data source attribute. The data element is an HTML5 attribute that allows you to generate your own properties for a tag. So the data source property doesn't really exist in HTML. It's something that I just made up. And you could do that by using data and then hyphen, and then whatever you want, and then define your own data. So what I wanted to do here is, when I click on any one of these elements, I wanted to pass along the location of the MP3 file to my JavaScript.

So that's why I added this tag right here. Now the CSS is also pretty mundane. So if you look down here at the bottom of the css you'll see that there are different states for showing how the different list items should look when they're being played or a song has been paused. Or while the sound is playing, so that's what all these styles are for down here. So let's go ahead and start coding. We'll go into our script file, which right now it's empty. And the first thing we're going to do, as usual, is create a variable.

And we'll call this one jukebox. And it's going to point to our UL with a class of player. So, document.queryselector. And it's going to call ul.player. Next we're going to add an event listener to the jukebox, so we'll say, jukebox.addEventListener. And what we want to check for is a click event when somebody clicks on one of the list items. And then we want to execute a function, pass it along an event and we want to make sure we also pass here the value of false so that it bubbles properly.

So, next we want to create the audio player which is going to be just an audio tag. So, we're going to say variable audio player and that's going to be equal to document and we're going to create this element, and it's going to be an audio tag. Next, we're going to change the ID of the audio element, this is going to be important later on, not right now, it's not really going to make a big difference. But it will be nice to be able to access this element later if we attach an ID element to it. So we're going to say.

Audio player.id, it's going to be player. So my audio player is going to have an ID of player. And then we're going to append this. So, document, we'll attach it to the body. So this is something that you haven't seen before. We're attaching the element, not to a previously existing element, like an overlay. Or not to, say the list item. We're just attaching it to the body. We don't really need it to be related to our list element but we do need it somewhere on the page. I don't want to put it right into a list element because we could be clicking on any one of these songs and I don't want the auto player to be on the first list item I click on.

I just want it to be somewhere on the page. So document body and then append child. And then we're going to pass it audio player. So that puts it on the screen. And let's go ahead and save that. I'm going to switch over to my project, and I'll refresh. And I want to right-click and pull up the developer tools, and click on the console. It looks like I have a little bit of a JavaScript error here, at event listner. Looks like I missed an e. So definitely we have to check for that. Add event listener. Okay, back over here, refresh, that's gone and let's just click on one of these images.

So, nothing is happening right now, hm, let's take a look at the elements. You can see that my audio players are being generated but no sound is playing. And now that's because we've generated the audio player, and we've appended it. We haven't really told it what to play, so I need to say something like, audio player, and then set the location of the auto player to be. I'm going to set it to something called song name, and I need to create this variable, so I'll do it right up here.

Variable song name. Is to be equal to, the target of what I click on. This time I'm going to use something called get attribute, and I'm going to find that attribute data that SRC and that's going to set our song name, and then we set the location of the sound to the song names. Let's go and save that and let's see whats happening now. Refresh, lets go and press the escape key in our developer tools. To get the console and the elements panel at the same time, and I'm going to click on this and see what's happening, well we're getting the audio with the right id and the right source location.

But it's not playing, and that's because to play a sound, you actually have to execute the play method of the sound. So to do that once I append the child I'm going to say audioPlayer and then execute the play command. And then I'm going to refresh this page. And I'll play this one because I know it's short. (MUSIC) If you get too tired of it just hit refresh and it'll stop playing the song for right now. This is one of the problems with this code right now it doesn't let you stop any of these.

(SOUND) And you can play more than one of them in a row. So we'll need to fix that eventually. But let me talk a little bit about what we did here. Now normally you can access any element or any property of an object by just using dot notations. So you could say something like e.target.src, but the data source attribute as we mentioned before is not a standard attribute. So we can't just say e.target. data.source, It doesn't really exist. And so to get to that attribute we have to use this notation.

Which is e.target and then get an attribute. You can also set an attribute if you want to. But this works pretty well. And the only thing you have to do is remember that you have to play this. So really playing a song isn't too hard. We can create a play event using the play method. And unfortunately this is going to make the song play at the same time as the other songs as you click on another element. And when a song stops playing, our player's not going to update. So, if we go over here and we play this song again. This is the shortest one. (MUSIC).

So, note that the audioplayer is still there, and it should really be gone. Another thing that we're not doing is identifying which song we're currently playing. So let's see, if you look at this is the song that is currently playing, so I should set the ID of this element to something like playing that will attach the proper style. Let's see. We need to do that. So actually we set the ID of the song to player, but we haven't set the ID of the element that we clicked on. So we should do that as well. So e.target.id.

And what you want to do is set it to one of the previous styles that you created for that. So remember, we have a playing ID style and if we do that it's going to look a little different. So, we need to this JavaScript, set this to plain. Right, and we refresh and we actually click on this, so see that. (MUSIC) it looks (MUSIC) Refreshed too, stop it. It looks a little bit different when we click on this. So, let's go and click it and we will wait until the end of it. (MUSIC).

(MUSIC) Alright, so when the song is over, the problem is it's not unplaying or unsetting this item is being played, and we still have the audio element here. This should be gone because the song is no longer playing. And if you open this up, you can see that we've got the ID right here on this element. This ID should be gone. Those are things we'll start to worry about in the next movie.

There are currently no FAQs about JavaScript: Events.

 
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ .

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

Join now Already a member? Log in

* Estimated file size

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed JavaScript: Events.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member ?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferences from the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Learn more, save more. Upgrade today!

Get our Annual Premium Membership at our best savings yet.

Upgrade to our Annual Premium Membership today and get even more value from your lynda.com subscription:

“In a way, I feel like you are rooting for me. Like you are really invested in my experience, and want me to get as much out of these courses as possible this is the best place to start on your journey to learning new material.”— Nadine H.

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.