Reputation: 59
Can anyone help me re-write the following code to work without using ID's, so that I can use this for multiple videos on a single page? Thank you in advance!!
HTML MARKUP
<div id="video-container">
<video id="video" width="640" height="365" src="https://d3vv6lp55qjaqc.cloudfront.net/items/3V3g280Q1z441P071g3E/tnt-lidcap-web.mp4" type="video/mp4" autoplay loop muted></video>
<div id="video-controls">
<button id="play-pause" type="button" aria-label="toggle pause play">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 120 120" width="120" height="120">
<circle cx="60" cy="60" r="60" fill="#000" fill-opacity=".5" />
<path stroke="#fff" stroke-linecap="round" stroke-width="10" d="M74.933 33v54M45.067 33v54" id="pauseIcon" class="video-pause" style="visibility: visible" />
<path fill="#fff" stroke="#fff" stroke-linejoin="round" stroke-width="8" d="M54 33L54 87 81 60z" id="playIcon" class="video-play" style="visibility: hidden" />
</svg>
</button>
</div>
</div>
JAVASCRIPT (WORKS FOR SINGLE VIDEO)
window.onload = function() {
var video = document.getElementById("video");
var playButton = document.getElementById("play-pause");
var pauseIcon = document.getElementById("pauseIcon");
var playIcon = document.getElementById("playIcon");
playButton.addEventListener("click", function() {
if (video.paused == true) {
video.play();
pauseIcon.style.visibility ="visible";
playIcon.style.visibility ="hidden";
} else {
video.pause();
pauseIcon.style.visibility ="hidden";
playIcon.style.visibility ="visible";
}
});
}
Here is a link to my current working CodePen as well:
https://codepen.io/jhughes1006/pen/yZPVGo
Upvotes: 0
Views: 984
Reputation: 1
You can substitute class
for each id
and use .querySelectorAll()
to perform the same task.
onload = e => {
const containers = document.querySelectorAll('.video-container'):
containers.forEach(container => {
const video = container.querySelector('video');
const playButton = container.querySelector('button');
playButton.addEventListener('click', e => {
// do stuff
})
})
}
Upvotes: 2
Reputation: 59
For anyone else's future reference, here is the new working code for multiple videos based on the answer given by @guest271314
onload = function onload(e) {
var containers = document.querySelectorAll(".video-container");
containers.forEach(function(container) {
var video = container.querySelector("video");
var playButton = container.querySelector("button");
var pauseIcon = container.querySelector(".pause-icon");
var playIcon = container.querySelector(".play-icon");
playButton.addEventListener("click", function(e) {
if (video.paused == true) {
video.play();
pauseIcon.style.visibility ="visible";
playIcon.style.visibility ="hidden";
} else {
video.pause();
pauseIcon.style.visibility ="hidden";
playIcon.style.visibility ="visible";
}
});
});
};
Upvotes: 1