onEnded problem

Have you put it inside $w.onReady?

$w.onReady(() => {
//here
})