lefunction
lefunction

Reputation: 301

Javascript not executing functions using = operator

I am new to javascript, so this is a basic question. I created a simple mp3 player that loads the first song, then plays the next couple songs in an array. I modified this code that I found on stack, and it works:

audioPlayer.onended = function() {
    if(currentSong < nextSong.length-1) {
        audioPlayer.src = nextSong[++currentSong];
        document.getElementById('songTitle').innerHTML 
                                = songTitle[currentSong];
    }
}

However, if I try to put the implementation in its own function and call the function that way it doesn't work:

audioPlayer.onended = nextSong();

function nextSong() {
    if(currentSong < nextSong.length-1) {
        audioPlayer.src = nextSong[++currentSong];
        document.getElementById('songTitle').innerHTML 
                                = songTitle[currentSong];
    }
}

I don't want to rewrite the code every time I want to use the function nextSong(). I have tried calling the nextSong() function from a button inside the tag, for example this post, but cannot get the function to call. Thanks for your help.

Upvotes: 0

Views: 42

Answers (1)

bvaughn
bvaughn

Reputation: 13497

This is a common confusion. What your second example is actually doing is running the nextSong function and assigning its return value to onended.

Instead, you could change your code to:

function nextSong() {
    if(currentSong < nextSong.length-1) {
        audioPlayer.src = nextSong[++currentSong];
        document.getElementById('songTitle').innerHTML 
                                = songTitle[currentSong];
    }
}

// Assign the function (nextSong) not its return value (nextSong())
audioPlayer.onended = nextSong;

Upvotes: 5

Related Questions