Getting Started with the JavaScript API

The new version 6 player uses the JavaScript API provided by JW Player. You can read about the different event listeners and callbacks here. In this article we will show you how to use the JavaScript API.

Displaying a Call to Action when the video ends

When a user finishes watching a video, you might want to display a call to action message to them. It could be a link to buy the content, more videos to keep the user on the site, or social media icons for them to share the video. In our example, we will display a message to the user when the video ends.

In order to use the JavaScript API correctly, you’ll need the player’s html id attribute. In our example the id attribute we use is example1. Below is the code you’ll use to listen for the player’s onComplete event.

jwplayer('example1').onComplete(function() {

});

Inside this method we can add the necessary code to display the message to the user.

jwplayer('example1').onComplete(function() {
var config = jwplayer('example1').config;
var width = config.width;
var div = document.createElement("div");
var styles = getStyles();

styles.width = (width-20) + "px"
setStyleCSS(div, styles);
div.innerHTML = "Display a call to action to your users.";

var parentDiv = document.getElementById('example1_wrapper');
parentDiv.appendChild(div)
});

function getStyles()
{
return {
height: "20px",
background: "#eeeeee",
color: "#353535",
padding: "10px",
border: "1px",
borderStyle: "dotted",
borderColor: "#bbbbbb"
};
}

function setStyleCSS(element, styles)
{
for(var s in styles) {
element.style[s] = styles[s];
}
}

When the video ends, a small message will be displayed to the user. That’s great we achieved our goal, but we’re not done yet. There’s a problem with our code. If the user replays the content the message will always be appended at the end of the player. In order to make sure this doesn’t happen we will use another API call to delete the div.
The event we want to capture is onPlay, this event triggers when the video starts playing. We don’t want this call  to be a global event because it will get called before we even show our call to action message. So we will place the event listener in the onComplete function callback.


jwplayer('example1').onComplete(function() {
var config = jwplayer('example1').config;
var width = config.width;
var div = document.createElement("div");
var styles = getStyles();

styles.width = (width-20) + "px"
setStyleCSS(div, styles);
div.innerHTML = "Display a call to action to your users.";

var parentDiv = document.getElementById('example1').offsetParent;
parentDiv.appendChild(div)

jwplayer('example1').onPlay(function() {
parentDiv.removeChild(div)
});

});