What is the best method for incorporating a YouTube embedded video into an image carousel using HTML and CSS?

I'm encountering an issue with my product carousel that includes an image and a video. The image displays correctly, but when I attempt to click on the video to have it appear in the main carousel view, it doesn't function as expected. Here is a snippet of my index.html code (I've excluded the actual video link):

<div id="content-wrapper">
    

    <div class="column">
        <img id=featured src="images/sample1.jpg">

        <div id="slide-wrapper" >
            

            <div id="slider">
                <img class="thumbnail active" src="images/sample1.jpg">
                <iframe class="thumbnail" width="560" height="315" src="videolink" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>
            </div>

        </div>
    </div>

    <div class="col-2">
        <p>Home / Sample Item 1</p>
        <h1>Sample Item 1</h1>
        <h4>$00.00</h4>
        <h3>Product Details</h3><br>
        <p>Manufactured in CANADA</p>
    </div>

</div>

In the same source code, I've included some Javascript:

<script type="text/javascript">
    let thumbnails = document.getElementsByClassName('thumbnail')

    let activeImages = document.getElementsByClassName('active')

    for (var i=0; i < thumbnails.length; i++){

        thumbnails[i].addEventListener('mouseover', function(){
            console.log(activeImages)
            
            if (activeImages.length > 0){
                activeImages[0].classList.remove('active')
            }
            

            this.classList.add('active')
            document.getElementById('featured').src = this.src
        })
    }

</script>

Here's my CSS code as well:

body{
    padding-top: 100px;
}

#content-wrapper{
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    align-items: center;
}

.column{
    width: 600px;
    padding: 10px;

}

#featured{
    max-width: 500px;
    max-height: 600px;
    object-fit: cover;
    cursor: pointer;
    border: 2px solid black;

}

.thumbnail{
    object-fit: cover;
    max-width: 180px;
    max-height: 100px;
    cursor: pointer;
    opacity: 0.5;
    margin: 5px;
    border: 2px solid black;

}

.thumbnail:hover{
    opacity:1;
}

.active{
    opacity: 1;
}

#slide-wrapper{
    max-width: 500px;
    display: flex;
    min-height: 100px;
    align-items: center;
}

#slider{
    width: 440px;
    display: flex;
    flex-wrap: nowrap;
    overflow-x: auto;

}

#slider::-webkit-scrollbar {
        width: 8px;

}

#slider::-webkit-scrollbar-track {
    -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3);

}
 
#slider::-webkit-scrollbar-thumb {
  background-color: #dede2e;
  outline: 1px solid slategrey;
   border-radius: 100px;

}

#slider::-webkit-scrollbar-thumb:hover{
    background-color: #18b5ce;
}

.arrow{
    width: 30px;
    height: 30px;
    cursor: pointer;
    transition: .3s;
}

.arrow:hover{
    opacity: .5;
    width: 35px;
    height: 35px;
}

While hovering over the image displays it correctly in the carousel view, hovering over the embedded video shows a broken image icon instead of the video itself. What could be causing this issue, and how can I rectify it to ensure the video displays properly upon hover?

Answer №1

After exploring a variety of options and experimenting with different approaches, I have arrived at a solution that may be helpful to you. By making adjustments to the CSS and positioning the elements accordingly, you can achieve the desired outcome.

  1. HTML:
<div class="container">
  <div class="box">
    <img src="ray-so-export.png">
    <iframe width="560" height="315" src="https://www.youtube.com/embed/cCYObFBEp0k" frameborder="0"
      allowfullscreen></iframe>
  </div>
  <div class="preview"></div>
</div>
  1. CSS:

.container {
display: flex;
}

.box {
width: 50%;
padding: 20px;
}

.box:hover {
cursor: pointer;
}

.preview {
display: flex;
justify-content: center;
align-items: center;
height: 300px;
background-color: lightgray;
}

.box img,
.box iframe,
.preview img,
.preview iframe {
width: 250px;
height: 250px;
object-fit: cover;
}
  1. Javascript:
var box = document.querySelector('.box');
var preview = document.querySelector('.preview');

box.addEventListener('mouseover', function(event) {
var target = event.target;

if (target.tagName === 'IMG' || target.tagName === 'IFRAME') {
var clone = target.cloneNode(true);
preview.innerHTML = '';
preview.appendChild(clone);
}
});

box.addEventListener('mouseleave', function() {
preview.innerHTML = '';
});

For further reference, you can view my CodePen demo. Please feel free to leave a comment if you have any additional questions or feedback.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing Radio buttons for validation in react-hook-form

After creating a form with radio buttons and implementing validation using React Hook Form, I encountered an issue where the console always displayed "on" regardless of the selected radio button. <div className=""> <label ...

How to retrieve specific items from an array contained within an array of objects using Express.js and MongoDB

Within the users array, there is an array of friends. I am looking to retrieve all friends of a specific user based on their email where the approved field is set to true. In my Node.js application, I have defined a user schema in MongoDB: const UserSchem ...

Creating a specialized pathway with variable inputs within the URL

As a Node beginner, I am facing a challenge with an Express exercise on dynamic routes. The task at hand is to create a route that can accept dynamic arguments in the URL path and respond with a quote from the respective author. Here's a snippet of th ...

Running concurrently, the JavaScript if and else statements execute together

I am looking to create a clickable link that changes the background color when clicked. If the same link is clicked again, I want the background to return to its original state. Here is my current script: <div style="background: transparent;" onclick=" ...

Another ajax function implemented for a different form is experiencing technical issues

I have two forms with different IDs (form_sign and form_login) and I am using AJAX to submit them. The form_sign is working fine, but the other form is not functioning properly. When I tried to display an alert after submitting the form_login function, it ...

Unable to get the desired 100px margin at the bottom

Can someone assist me in positioning the right side image at the bottom of the div tag using CSS? I have tried using the .up class in my style tag but with no success. How can I achieve this by adjusting the margin? <!DOCTYPE html> <html lang=" ...

Having issues with implementing Bootstrap 4 dynamic nav-pills in PHP CodeIgniter

When I select different product categories, only the items from the active category are displayed. When I click on another nav-item, the previously displayed items remain unchanged and I'm unable to change the class "show active" in the tab-panes. Co ...

Unable to insert an array within a function

I've searched for the answer but couldn't find it - my array is not pushing to datahasil. How can I push the array hasil into datahasil...?? const data1 = await JadwalBooking.aggregate([{ $project: { "keterangan": "$keterangan", ...

Using CSS, create a layout with a small 2x2 box positioned beside a larger 2x2 box

Can a flexible ul li structure be achieved with flexbox? I attempted to set the width of the squares to 25% and make the 1st, 3rd, or 5th one 50% wide using a combination of float:left, clear[left|right], but the last square ends up dropping to a single ro ...

Adjust the overflow to automatically decrease at regular intervals

Is there a way to make the scroll automatically move down a bit every few seconds, revealing more text in the process? Here's an example of how I want it to work: http://jsfiddle.net/Bnfkv/2/ ...

Exploring ways to access an element's background color through JavaScript

Is there a way to access an element's CSS properties that are set by a class name in JavaScript? In the case of the first div element, I have applied a "red" class which sets its background color to red. However, when I try to access the div's b ...

Trigger a Tabulator event when a checkbox is selected in Vue 3

Currently, I am utilizing Vue3 along with Tabulator (5.2.7) to create a data table using the Composition API. In the following code snippets, I have excluded irrelevant parts of the code. //DataTable.vue <script setup> import { TabulatorFull as Tabu ...

Adjust the input dimensions to match the length of the text upon loading

I have a jQuery code that is supposed to test the length of text in an input box when the page loads and adjust the size of the input box accordingly. However, I seem to be encountering some issues with my current approach: $("#emailSubject").attr('s ...

Uploading files asynchronously in Internet Explorer 8

Currently, I am on the lookout for sample code that allows asynchronous file uploads in IE8 using Ajax. While having upload progress would be a bonus, it is not essential. Moreover, I specifically need PHP code to handle the uploaded files on the server ...

CSS animation for horizontal scrolling with sticky positioning is not functioning as intended

I've designed a creative way to achieve infinite horizontal scrolling using CSS animation, and my goal is to make the first element in the list stick in place. Everything works smoothly when I utilize the left property within the @keyframes. However, ...

How to style CSS to ensure printed table content fits perfectly within the page

Does anyone know how to resize the contents of a table using CSS so that everything shows up when printing, without wrapping text in individual cells? In this scenario, <table class="datatables" id="table1"> <tr> <td style="white-space:nowr ...

Is there a way to incorporate multiple functions into a single sx property, such as color, zIndex, backgroundColor, etc? Can this be achieved in any way?

I am currently developing a single search component that will be used across various sections of my application. Each component receives a prop called search: string to determine its type and apply specific styles accordingly. Although I could use classNam ...

Having trouble updating the URL path with the $location service in Angular

I'm facing a challenge in updating the URL path using the $location.url service, as it's not reflecting the changes correctly. For instance, my current URL path is http://localhost:64621/module/commercial/#/company/98163780-4fa6-426f-8753-e05a6 ...

Encountering challenges with web scraping certain data that is not being captured after a line break tag using Python's

I've been attempting to scrape a public web directory in order to retrieve contact information for companies. While my code is functioning properly, it seems to be having trouble extracting information that comes after the br tag. For example, it fai ...

What is the reason for Vue not updating the component after the Pinia state is modified (when deleting an object from an Array)?

When using my deleteHandler function in pinia, I noticed an issue where the users array was not being re-rendered even though the state changed in vue devtools. Interestingly, if I modify values within the array instead of deleting an object from it, Vue ...