javascripteventsevent-handlingdom-eventsjwplayer

JWplayer multiple player in one page and event handler


Scenario

I have multiple players in the same page. Each instance loads a different video. I need to handle similar events for every instance.

Problem

If I just declare the events on a general function – like this jwplayer().on('play', handler) – the handler affects only the first player of the page.
If I declare the player's id the console returns:

Uncaught TypeError: jwplayer("text").on is not a function(anonymous function)


Solution

  • When you first create JW Player, you can get an object back and store it in a variable.

    var myJwPlayerInstance = jwplayer("JWPlayerDiv").setup({ ... });
    ...
    myJwPlayerInstance.on("play", function () { ... });
    

    You can do this for each JW Player instance you have, using separate variables or an array.