Reputation: 119
So I ran into an issue with assigning an event listener to my audio elements to allow them to auto-play on ending, after enough messing around I got it to work but I still don't get one thing. Why does $(this).get(0)
work but $(this).get()
not?
$('.song audio').each(function(){
$(this).get(0).addEventListener('ended' ,function(){
var target = $('.song.selected').next('.song');
if ($('.song').last().children('.title').text() == $('.selected').children('.title').text()) {}
else {
stopSelected();
changeSelected(target);
playNew();
currentlyPlaying();
resetTrack();
startSelected();
}
});
});
Upvotes: 0
Views: 85
Reputation: 65806
.get()
requires an index that corresponds to an element within the JQuery wrapped set of elements to "get" for you. Without an index, it doesn't know which one you want and so it returns an array of all the elements and an array doesn't have an .addEventListener()
method to call.
You can see that the array is returned in the following:
console.log($("p").get());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
Upvotes: 1
Reputation: 42054
These two lines:
$('.song audio').each(function(){
$(this).get(0).addEventListener('ended' ,function(){
can be reduced to:
$('.song audio').on('ended' ,function(){
Moreover, you can use the second argument of .each():
$('.song audio').each(function(idx, ele){
ele.addEventListener('ended' ,function(){
or, directly the this keyword
Upvotes: 0
Reputation: 24965
get()
returns an array. get(#)
returns a single element of the found elements. As such, since you are trying to do a dom method off of the operation, addEventListener
is not a valid method off of an array.
Upvotes: 1