WPDD

WordPress Develop & Design

iframe auto play from data-src

js vanilla. Please write js vanilla code that when user click the a tag with data-src value the script replace the content of the a tag with iframe tag with the data-src value and play it.

document.addEventListener('click', function(event) {
    // Check if the clicked element is an <a> tag with a data-src attribute
    const link = event.target.closest('a[data-src]');
    
    if (link) {
        event.preventDefault(); // Prevent the default action of the link
        
        // Get the data-src value
        let videoSrc = link.getAttribute('data-src');
        
        // Append autoplay query parameter to the video URL
        if (videoSrc.includes('?')) {
            videoSrc += '&autoplay=1';
        } else {
            videoSrc += '?autoplay=1';
        }
        
        // Create an iframe element
        const iframe = document.createElement('iframe');
        iframe.setAttribute('src', videoSrc);
        iframe.setAttribute('frameborder', '0');
        iframe.setAttribute('allow', 'accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture');
        iframe.setAttribute('allowfullscreen', 'true');
        iframe.style.width = '100%';
        iframe.style.height = '100%';
        
        // Clear the content of the <a> tag and append the iframe
        link.innerHTML = '';
        link.appendChild(iframe);
    }
});