Reputation: 91
I have two arrays.One of videos and one of images. I need to play only one video at a time when image is clicked. Like if clicked on img[1] then it should play video[1] and if img[2] then video[2].
I need to do something like this : IMAGE
I have gone through few examples but didn't find any similar answer using only javascript. Now when i click on image it opens anchor tag link which i have added for testing but not able to play videos.
var videosList = [
"http://media.w3.org/2010/05/sintel/trailer.mp4",
"http://media.w3.org/2010/05/bunny/trailer.mp4",
"http://vjs.zencdn.net/v/oceans.mp4"
];
var allVideos = videosList.length;
var i = 0;
for (; i < allVideos; i++) {
var vid = document.createElement('source');
vid.src = videosList[i];
document.getElementById('myVideo').appendChild(vid);
}
var images = [
'https://picsum.photos/200/300',
'https://picsum.photos/id/237/200/300',
'https://picsum.photos/200/300?grayscale',
'https://picsum.photos/id/237/200/300',
'https://picsum.photos/200/300'
];
var allPics = images.length;
var i = 0;
for (; i < allPics; i++) {
var a = document.createElement('a');
a.href = 'example.html';
var img = document.createElement('img');
img.src = images[i];
a.appendChild(img);
document.getElementById('myImg').appendChild(a);
}
Here is running code as example:codepen
Upvotes: 0
Views: 719
Reputation: 160
// JavaScript can be change in the following way
// Assuming that the video to be played is the same as index of the image clicked
// make it as global to access in all functions
var videosList = [
"http://media.w3.org/2010/05/sintel/trailer.mp4",
"http://media.w3.org/2010/05/bunny/trailer.mp4",
"http://media.w3.org/2010/05/bunny/movie.mp4",
"http://vjs.zencdn.net/v/oceans.mp4"
];
window.onload = function() {
// for videos
var vid = document.createElement('source');
vid.src = videosList[0]; // playing first video in the array by default
document.getElementById('myVideo').appendChild(vid);
// for images
var images = [
'https://picsum.photos/200/300',
'https://picsum.photos/id/237/200/300',
'https://picsum.photos/200/300?grayscale',
'https://picsum.photos/id/237/200/300',
'https://picsum.photos/200/300'
];
var allPics = images.length;
var i = 0;
for (; i < allPics; i++) {
var a = document.createElement('a');
// a.href = 'example.html';
var img = document.createElement('img');
img.src = images[i];
img.id = i; // for the reference of clicked image
a.appendChild(img);
a.addEventListener("click", clickFn, false);
document.getElementById('myImg').appendChild(a);
}
}
/**click function for the image of the image */
clickFn = function(e){
var video = document.getElementById('myVideo');
video.src = videosList[parseInt(e.srcElement.id,10)];
video.play();
}
Hope it helps ..!!
modified code in codepen
Upvotes: 1