#1 by WD95
Hi everyone,
I'm embedding a YouTube video on a page and want to achieve the following:
The video should autoplay with sound when participants enter the page.
Participants should not be able to pause the video.
I'm currently facing the following issue: due to browser restrictions, if the video has sound, the autoplay=1 command doesn't execute, and the video doesn't autoplay. However, if I set mute=1, the video autoplays, but it remains muted since the control buttons are hidden.
Is there any way to achieve both autoplay with sound? Can we unmute the video after a few seconds of playback?
Here is my current code:
<script>
// Array of video sources with autoplay parameter for YouTube embed
const videoSources = [
{% for video in videos_to_play %}
"{% video %}",
{% endfor %}
];
// Function to create draggable video popup
function createVideoPopup(videoSrc) {
// Create a popup element for the video
let popup = document.createElement('div');
popup.className = 'video-popup';
popup.style.left = `760px`; // Random initial left position
popup.style.top = `300px`; // Random initial top position
// Use an iframe to embed the YouTube video
popup.innerHTML = `
<iframe width="560" height="315" src="${videoSrc}&autoplay=1&controls=0" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
`;
// Make popup draggable
makeDraggable(popup);
// Add popup to video-container
document.getElementById('video-container').appendChild(popup);
}
// Function to make an element draggable
function makeDraggable(element) {
let offsetX = 0, offsetY = 0;
element.addEventListener('mousedown', startDragging);
function startDragging(event) {
event.preventDefault();
offsetX = event.clientX - element.getBoundingClientRect().left;
offsetY = event.clientY - element.getBoundingClientRect().top;
document.addEventListener('mousemove', drag);
document.addEventListener('mouseup', stopDragging);
}
function drag(event) {
let x = event.clientX - offsetX;
let y = event.clientY - offsetY;
element.style.left = x + 'px';
element.style.top = y + 'px';
}
function stopDragging() {
document.removeEventListener('mousemove', drag);
document.removeEventListener('mouseup', stopDragging);
}
}
// Function to show random video popup
function showRandomVideoPopup() {
let randomIndex = Math.floor(Math.random() * videoSources.length);
createVideoPopup(videoSources[randomIndex]);
}
// Call showRandomVideoPopup when the page loads
window.addEventListener('load', function() {
showRandomVideoPopup();
});
</script>
Thank you very much for your help!