The change in image is not being implemented

When hovering over a list item, I want to display the corresponding image. While I have this functionality working, the issue lies in the CSS transition not functioning as expected. Should I incorporate a CSS selector or can the transition be added through JavaScript?

I'm unsure how to address this problem, so any suggestions or guidance would be greatly appreciated. Thank you.

This is being implemented using Bootstrap v5.3.0 alpha-1.

const test_list_items = document.querySelectorAll('.test_list_item');

test_list_items.forEach(element => {
    element.addEventListener('mouseover', () => {
        let previous_item = document.querySelector('.test_list_item.selected');
        let current_item = element;

        let previous_image = document.querySelector(`#test_image_${previous_item.id.slice(-1)}`);
        let current_image = document.querySelector(`#test_image_${element.id.slice(-1)}`);

        if (previous_item && previous_item.id !== current_item.id) {
            let selected_item = current_item.id;
            console.log(selected_item);
            console.log(`previous image: ${previous_image.id}`);
            console.log(`previous image: ${current_image.id}`);

            previous_item.classList.remove('selected');
            current_item.classList.add('selected');

            // previous_image.style.opacity = 0;
            previous_image.classList.remove('d-md-block');
            // current_image.style.opacity = 1;
            current_image.classList.add('d-md-block');
        }
    });
});
.test_image .d-md-block {
    /* position:absolute; */
    /* opacity:1; */
    /* transition: opacity 0.5s linear; */
    transition-timing-function: opacity 3s ease-in;
}
        <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cdafa2a2b9beb9bfacbd8df8e3fee3fde0aca1bda5acfc">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
        <link rel="stylesheet" href="{{ url_for('static', filename='css/index.css') }}" />
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="22404d4d5651565043520f4b414d4c5162130c13120c11">[email protected]</a>/font/bootstrap-icons.css">

<section class="p-5">
    <div class="container">
        <h2 class="text-center display-5 fw-bold">test</h2>
        <p class="lead text-center mb-5">
          esstsgsgsgsgsgesgsgsgegsgsgesgsgsgessegsgsg
        </p>

        <div class="row g-4 justify-content-between">
            <div class="col-md">
                <div class="list-group list-group-flush">
                    <a href="#" class="list-group-item list-group-item-action d-flex justify-content-between align-items-start test_list_item selected" id="test_list_item_1">
                        <span class="badge">
                            <img src="https://cdn.shopify.com/s/files/1/1218/4290/products/Solid-101-DeepRed_1400x.jpg" style="height: 50px; width: 50px;">
                        </span>
                        <div class="ms-2 me-auto">
                            <div class="d-flex w-100">
                                <h5 class="mb-1">1</h5>
                            </div>
                            Content for list item
                            Content for list item
                            Content for list item
                            Content for list item
                            Content for list item
                            <!-- <p class="mb-1 text-muted">Some placeholder content in a paragraph.</p> -->
                        </div>
                    </a>

                    <a href="#" class="list-group-item list-group-item-action d-flex justify-content-between align-items-start test_list_item" id="test_list_item_2"> 
                        <span class="badge">
                            <img src="https://www.jbcandcompany.com/images/S%20Orange.png" style="height: 50px; width: 50px;">
                        </span>
                        <div class="ms-2 me-auto">
                            <div class="d-flex w-100">
                                <h5 class="mb-1">2</h5>
                            </div>
                            Content for list item
                            Content for list item
                            Content for list item
                            Content for list item
                            Content for list item
                            <!-- <p class="mb-1 text-muted">Some placeholder content in a paragraph.</p> -->
                        </div>
                    </a>

                    <a href="#" class="list-group-item list-group-item-action d-flex justify-content-between align-items-start test_list_item" id="test_list_item_3">
                        <span class="badge">
                            <img src="https://cdn.shopify.com/s/files/1/1218/4290/products/Solid-125-BrightPink_1024x.jpg" class="rounded-0" style="height: 75px; width: 75px; background-color: yellow;">
                        </span>
                        <div class="ms-2 me-auto">
                            <div class="d-flex w-100">
                                <h5 class="mb-1">3</h5>
                            </div>
                            Content for list item
                            Content for list item
                            Content for list item
                            Content for list item
                            Content for list item
                            <!-- <p class="mb-1 text-muted">Some placeholder content in a paragraph.</p> -->
                        </div>
                    </a>
                </div>
            </div>

            <div class="col-md">
                <div class="image_container">
                    <img src="https://cdn.shopify.com/s/files/1/1218/4290/products/Solid-101-DeepRed_1400x.jpg" class="test_image d-none d-md-block active" id="test_image_1" style="height: 500px; width: 700px;" />
                    <img src="https://www.jbcandcompany.com/images/S%20Orange.png" class="test_image d-none" id="test_image_2" style="height: 500px; width: 700px;" />
                    <img src="https://cdn.shopify.com/s/files/1/1218/4290/products/Solid-125-BrightPink_1024x.jpg" class="test_image d-none" id="test_image_3" style="height: 500px; width: 700px;" />
                </div>
            </div>
        </div>
    </div>
</section>

        <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3b5954544f484f495a4b7b0e1508150b165a574b535a0a">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script>
        <script type="text/javascript" src="{{ url_for('static', filename='script/index.js') }}"></script>

Answer №1

To achieve this effect, simply add or remove the fadeIn animation in your code:

const items = document.querySelectorAll('.item');

items.forEach(item => {
    item.addEventListener('mouseover', () => {
        let previousItem = document.querySelector('.test_list_item.selected');
        let currentItem = item;

        let previousImage = document.querySelector(`#img_${previousItem.id.slice(-1)}`);
        let currentImage = document.querySelector(`#img_${item.id.slice(-1)}`);

        if (previousItem && previousItem.id !== currentItem.id) {
            let selectedItemId = currentItem.id;
            console.log(selectedItemId);
            console.log(`previous image: ${previousImage.id}`);
            console.log(`current image: ${currentImage.id}`);

            previousItem.classList.remove('selected');
            currentItem.classList.add('selected');

            // Hide previous image
            previousImage.classList.remove('show');
            previousImage.classList.remove('fade-in');

            // Show current image with fade-in effect
            currentImage.classList.add('show');
            currentImage.classList.add('fade-in');
        }
    });
});
.fade-in {
  animation: fadeIn 5s;
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
        <link rel="stylesheet" href="{{ url_for('static', filename='css/index.css') }}" />
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/font/bootstrap-icons.css">

<section class="p-5">
    <div class="container">
        <h2 class="text-center display-5 fw-bold">Test Section</h2>
        <p class="lead text-center mb-5">
          Content goes here.
        </p>

        <div class="row g-4 justify-content-between">
            <div class="col-md">
                <div class="list-group list-group-flush">
                    <a href="#" class="list-group-item list-group-item-action d-flex justify-content-between align-items-start item selected" id="item_1">
                        <span class="badge">
                            <img src="image1.jpg" style="height: 50px; width: 50px;">
                        </span>
                        <div class="ms-2 me-auto">
                            <div class="d-flex w-100">
                                <h5 class="mb-1">1</h5>
                            </div>
                            Detailed content for item 1
                        </div>
                    </a>
                    
                    <!-- Additional list items go here -->

                </div>
            </div>

            <div class="col-md">
                <div class="image-container">
                    <img src="image1.jpg" class="image show" id="img_1" />
                    <img src="image2.jpg" class="image" id="img_2" />
                    <img src="image3.jpg" class="image" id="img_3" />
                </div>
            </div>
        </div>
    </div>
</section>

        <script src="https://cdn.jsdelivr.net/npm/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
        <script type="text/javascript" src="{{ url_for('static', filename='script/index.js') }}"></script>

Answer №2

To ensure a smooth transition when scrolling, remember to initially set the opacity to 0 and then change it to 1 once you start scrolling. Failing to do so may result in the transition not functioning correctly.

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

The export of 'alpha' is not available in the '@mui/system' module

Help! I am encountering an error related to the @mui/material library. I have already looked into the package.json file of mui/system and it seems that 'alpha' is exported in it. ./node_modules/@mui/material/styles/index.js Attempted import erro ...

How to Customize Bootstrap 4 Form Styles

Looking to customize the appearance of a checkbox in a web framework utilizing bootstrap 4, I attempted to override the custom-control-label class by setting the position property to auto instead of its default value of relative. Although I achieved the ...

The expiration time and date for Express Session are being inaccurately configured

I'm experiencing an issue with my express session configuration. I have set the maxAge to be 1 hour from the current time. app.use( session({ secret: 'ASecretValue', saveUninitialized: false, resave: false, cookie: { secure ...

JavaScript: Array methods and Functions

export function getPlanetNames(data) { const pNames = data.planets; const results = pNames.filter(function (getNames) { return getNames.name; }); return results; 'data' is stored in a separate file and consists of an object array wit ...

The code for the bouncing image isn't functioning properly outside of the JSFiddle environment

I'm having issues with this jQuery snippet in my web application. It works fine on jsfiddle, but not when I add it to my project. Here's the code: $('.myimage').mouseenter(function() { $(this).effect('bounce',500); }); Her ...

Is Mongodb making an asynchronous request?

How can I ensure synchronous execution of code in this scenario? Despite trying various methods, the issue persists where res.render is called too early and certain objects from state are missing. The playingCollection refers to a MongoDB collection. va ...

Guide to adjusting the map zoom speed on Mapbox using mouse scroll

I am a user of mapbox () and I am looking to adjust the zoom speed of the map when scrolling with the mouse. It seems like the API documentation does not have an option to control the zoom speed directly, unless it is done through something like the flyTo( ...

Vue 3's click event handler does not recognize $options.x as a valid function

I'm encountering a perplexing issue. I am currently in the process of creating a Wordpress plugin using Vue, but unfortunately, I am unable to establish functionality for the @click event. <script> export default { name: "App", me ...

display rails view using ajax

I have developed a new form that I would like to render using ajax in case it fails validations. In my controller, the code looks like this: def create event = CEvent.new(params[:c_event]) respond_to do |format| if event.save format.html { ...

Join the geomarkers in two datasets using connecting lines

I am currently developing a leaflet.js map incorporating two distinct sets of JSON data layers stored as js-files. The first dataset comprises the geographical locations of various newsrooms along with their respective IDs, while the second dataset contai ...

Navigating Django's Pagination feature alongside nested tabs requires a combination of careful planning

I am in the process of enhancing my template by adding pagination functionality. The template consists of Nested Tabs, each containing a table. My goal is to implement pagination for all tables within the inner tabs. Currently, I have successfully added p ...

Dealing with XMLHttpRequest timeout issues in a React.js application

Within my react.js project, I have a function named getData in the Profile class. Here is how it appears: getData() { console.log("inside get data"); var request = new XMLHttpRequest(); request.timeout=1000; request.ontimeout=function () { ...

Is there a way to enclose a mention within a unique span tag after highlighting it? Similar to how tags are implemented on platforms such

Currently utilizing an AngularJS plugin called ment.io for incorporating mentions. However, I am having difficulty figuring out how to customize the appearance of the selected mention. For example, in Stackoverflow: https://i.sstatic.net/bZrkh.png Or i ...

What is preventing me from utilizing global variables in distinct HTML and JavaScript files?

I am facing a perplexing issue with my HTML files, specifically index.html and lobby.html. Within main.js, which is loaded in index.html, I attempt to load lobby.html using window.location.href. Despite trying various methods to define global variables i ...

Tips on Utilizing If/Else Conditions in HTML Table TD_TAGS

Can someone please explain how to implement an if/else condition within this <td> tag? <td data-label="Status">{{$t('Status'+item.cStatus)}}</td> This is what I am trying to achieve: if(item.cStatus == NW){ color:red ...

Transmitting an "array with key-value pairs" through POST method in AngularJS

Currently, I have a filter object that looks like this: { name: 'text', value: 'xxx', field: 'firstname' } This object represents a filter for a specific field and is updated whenever input field values change. I am at ...

What is the best way to incorporate a countdown timer on an ASP.NET webpage?

Looking to display a countdown timer in the top right corner of my ASP page that starts from 00:00:30 and counts down to 00:00:00 before resetting back to 00:00:30. Does anyone have any suggestions on how to achieve this? ...

Editing HTML on an ASPX website can be a breeze with

Hello there, I've been tasked with editing a website for a client, but the site is located on a local web server and was designed using aspx. As I review all the files, I am encountering difficulty finding the HTML code associated with runat=server w ...

Issues with Mega Menu functionality preventing items from being clickable and links from properly navigating

Recently, I encountered a strange issue related to the integration of a mega menu found at . Unfortunately, despite integrating the mega menu, the Category and sub category links seem unresponsive - they are not directing me to the desired links. I suspec ...

Display the X button solely once text has been inputted into the textbox

I have integrated a text clearing plugin from here in my project to allow users to clear the input field by clicking on an X button. However, I want to modify the code so that the X button only appears when there is text entered in the textbox. I attempt ...