I need to add videojs player dynamically by JavaScript. The problem is that after adding player to the page it does not work. It works perfect if it is placed manually but don't work if the code of the player added by JS. I guess there should be a kind of in it but can't find how to do it. Please help
<html lang="en">
<head>
<meta charset="utf-8">
<title>Page1</title>
</head>
<style>
/* * The body style is just for the
* background color of the codepen.
* Do not include in your code.
*/
body {
background-color: #111;
color: #fff;
}
/*
* Styles essential to the sample
* are below
*/
.video-js {
width: 640px;
height: 360px;
}
</style>
<body style="margin: 0px;">
<button onclick="addPlayer()">Add Player</button>
<div id="content"></div>
<div>
<div style="max-width: 960px;">
<video-js data-account="81247437001" data-player="bGqjsTYP" data-embed="default" controls="" data-video-id="6141765796001" data-playlist-id="" data-application-id="" class="vjs-fluid"></video-js>
</div>
<script src="https://players.brightcove.net/81247437001/bGqjsTYP_default/index.min.js"></script>
</div>
<script>
var cnt = 0;
function addPlayer() {
var jsc = "script";
var content =
`
<div style="max-width: 960px;">
<video-js id="pl_${cnt}" data-account="81247437001" data-player="bGqjsTYP" data-embed="default" controls="" data-video-id="6141765796001" data-playlist-id="" data-application-id="" class="vjs-fluid"></video-js>
</div>
<${jsc} src="https://players.brightcove.net/81247437001/bGqjsTYP_default/index.min.js"></${jsc}>
`
document.getElementById("content").innerHTML += content;
cnt++;
}
</script>
</body>
</html>
Don't include the script each time, you only need it once. After adding the element, use the bc()
method to initialise it. e.g.
function addPlayer() {
var jsc = "script";
var content =
`
<div style="max-width: 960px;">
<video-js id="pl_${cnt}" data-account="81247437001" data-player="bGqjsTYP" data-embed="default" controls="" data-video-id="6141765796001" data-playlist-id="" data-application-id="" class="vjs-fluid"></video-js>
</div>
`
document.getElementById("content").innerHTML += content;
bc(`pl_${cnt}`);
cnt++;
}