Adding an image to a div and slowly revealing it:

I'm currently working on creating an image slider. When I click on a thumbnail above, I retrieve the source of that image and append it to the designated div to display as a larger image. While this functionality is working, I'd like to enhance it by adding a fade-in effect when appending the new image and have the previous one fade out when a new image is clicked. How can I accomplish this?

Image Slider:

 <div id='main'>
        <div class="thumbsImg">
            <ul class="ulthumbs">
                <li>
                    <img src="img/a1.jpg" width='150' height="80">
                </li>
                    <li>
                        <img src="img/a2.jpg" width='150' height="80">
                    </li>
                    <li>
                        <img src="img/a3.jpeg" width='150' height="80">
                    </li>
                    <li>
                        <img src="img/a4.jpg" width='150' height="80">
                    </li>
                    <li>
                        <img src="img/a5.png" width='150' height="80">
                    </li>
                    <li>
                        <img src="img/a6.jpg" width='150' height="80">
                    </li>
                    <li>
                        <img src="img/a7.jpg" width='150' height="80">
                    </li>
                    <li>
                        <img src="img/a8.jpg" width='150' height="80">
                    </li>
                    <li>
                        <img src="img/a9.jpg" width='150' height="80">
                    </li>
            </ul>
        </div>            
        <div id='imgBody'></div>
    </div>

CSS

.thumbsImg {
  margin-left: auto;
  margin-right: auto;   
  width: 100%;
  overflow-x: auto;
  }

ul.ulthumbs {
  margin: 0;
  padding: 0;
  list-style: none;
  white-space: nowrap;
}
ul.ulthumbs li {
  display: inline-block;
  cursor: pointer;
}

#imgBody{
    overflow: hidden;
    margin-top: 15px;
    width: 100%;
    height: 70%;
    background-color: pink;

}

JS

  $(document).ready(function (){

    $('.ulthumbs li img').on('click', function(){


       $('#imgBody').html('');
       var imgSrc = $(this).attr('src');

       var img = "<img src='"+imgSrc+"' width='100%' height='auto'>";

       $('#imgBody').append(img);


    });

});

Answer №1

If you want to enhance your JQuery script, consider incorporating the fadeOut() and fadeIn functions.

For more information on these functions, please visit this link.

$('.ulthumbs li img').on('click', function(){
  $( "#imgBody" ).fadeOut( "slow" );
   $('#imgBody').html('');
   var imgSrc = $(this).attr('src');
   var img = "<img src='"+imgSrc+"' width='100%' height='auto'>";
   $( "#imgBody" ).fadeIn( "slow" );
   $('#imgBody').append(img);
});

To see this code in action, check out the demo on Codepen.

You also have the option to customize the fade-in/out duration according to your preference.

Answer №2

Regrets for not presenting this using JQuery, as I am not well-versed in it; however, it should be relatively simple to "translate" the code.

The concept here is to initially have an "empty" placeholder image with opacity set to 0 within the #imgBody element instead of appending a new img element with each click. Upon the first image click, the src property is assigned the clicked image's source, and the class that adjusts the opacity is removed. Subsequently, on each additional image click, the opacity-setting class is added back, the src is changed, and then the class is removed again.

((img,wait,first)=>document.querySelector(".ulthumbs").addEventListener("click",evt=>{
    if(!wait){
        wait=1;
        if(!first)img.classList.add("hide");
        setTimeout(()=>{
            img.src=evt.target.src;
            img.classList.remove("hide");
            setTimeout(()=>first=wait=0,first?0:500);
        },first?0:500);
    }
},0))(document.querySelector("#imgBody>img"),0,1);
.thumbsImg{
  margin:0 auto;
  overflow-x:auto;
  width:100%;
}
ul.ulthumbs{
  list-style:none;
  margin:0;
  padding:0;
  white-space:nowrap;
}
ul.ulthumbs>li{
  cursor:pointer;
  display:inline-block;
}
#imgBody {
  background:pink;
  margin-top:15px;
  overflow:hidden;
  width:100%;
}
#imgBody>img{
  height:auto;
  transition:opacity .5s;
  width:auto;
  max-width:100%;
}
#imgBody>img.hide{
  opacity:0;
}
<div id='main'>
    <div class="thumbsImg">
        <ul class="ulthumbs">
            <li><img src="https://unsplash.it/600/320?image=0" width='150' height="80"></li>
            <li><img src="https://unsplash.it/600/320?image=10" width='150' height="80"></li>
            <li><img src="https://unsplash.it/600/320?image=20" width='150' height="80"></li>
        </ul>
    </div>
    <div id="imgBody">
        <img class="hide" height="320" src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" width="600">
    </div>
</div>

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

Using jQuery Flot to dynamically load data onto the x-axis from an array

I have a jQuery flot graph that loads the x-axis data as follows: xaxis: { tickColor: 'transparent', tickDecimals: 0, ticks: ticks }, When I manually set the ticks variable like this, everything works fine and the x-axis displays the 7 da ...

Tips for adding HTML table information to a database

I have a table in HTML where one column can be edited, and I need to save that data into my database. Firstly, here is the code snippet: var tableData = [{ "Item Code": "C001", "Item Name": "Beverages", "Quantity": "0" }, { ...

What are some ways to utilize symbol fonts such as marvosym within a web browser?

Are you looking to use special LaTeX fonts like \Pluto from marvosym in your web development projects? Wondering how to display this symbol with HTML / JavaScript / CSS without relying on an image? You can download the font from This symbol corresp ...

Tips for changing color when hovering over elements in a CSS grid

I am currently attempting to incorporate a hover effect into this CSS grid, but I have not been successful in my efforts. I experimented with transition and opacity techniques, but they did not work as expected. Can someone please point out what I may be ...

Having difficulty decoding audio streams in Flask Socket.IO due to a file received by the Python server

Thank you for taking the time to go through this post. I have been diligently working on a project that involves capturing audio input from the client side and then sending the recorded audio to a Python server for analysis. However, I have hit a roadblock ...

How to replicate HTML5 pattern attribute functionality for input fields in web2py?

I want to ensure that all my forms are validated using the HTML5 pattern attribute, but I know that not all browsers support HTML5. So, I need a backup plan for those users who don't have modern browsers. Although I've written the code in two di ...

"angular-seed's web-script.js and cross-origin resource sharing (cors

I'm having trouble for the second day... I'm attempting to retrieve some json from an external domain, but I'm facing CORS issues. I believe that the problem lies with my node.js server not sending Origin: http://api.bob.com I've res ...

Inability to load a MySQL table using Ajax on the same webpage

I'm facing an issue where I want to load a table from mySql on the same page without getting redirected to another page. The user selects a date range, and upon pressing submit, it should appear in the designated div id tag. However, the functionality ...

Placing a pair of labels onto a bootstrap form while ensuring column alignment

I'm trying to format a form according to my UI/UX specifications, where there is a parent label and two sub-labels. Can this be achieved using Bootstrap? https://i.stack.imgur.com/J8wJZ.png However, I'm struggling to align the columns and rows ...

Achieve a dynamic effect by filling a path with an image and stretching it within the Canvas element

I am looking to fill a path in the shape of a circle or custom design with an image, but I want the image to stretch so that it fits within the boundaries of the closed path. Is it possible to accomplish this using HTML5 and the Canvas object? Below is th ...

Is there a way to extract a username from LDAP?

Can you help me understand how to dynamically retrieve a username from LDAP? In the code snippet below, I have hardcoded the username as 'smith2': $_SERVER["REMOTE_USER"] = 'smith2'; $param = $_SERVER["REMOTE_USER"] By using this appr ...

Issue with applying value changes in Timeout on Angular Material components

I'm currently experimenting with Angular, and I seem to be struggling with displaying a fake progress bar using the "angular/material/progress-bar" component. (https://material.angular.io/components/progress-bar/) In my "app.component.html", I have m ...

Unable to retrieve selected value with AJAX

My select box is set up with some values, and I'm using AJAX to send data to PHP and display that data inside a <div>. However, my code doesn't seem to be working properly. Interestingly, when I used a button to get the value from the sele ...

Can you customize the background color for the entire section where the first child appears in a nested collapsible list with CSS?

In my current setup, I have a nested list within a larger container box. Each ul element has a border-top style applied, while each li element has a border-bottom and padding. The HTML code looks like this: <div class="menu"> <ul ...

Troubles encountered when loading pages into a div using ajax navigation

As someone new to the world of programming, I am embarking on the journey of creating a simple website for myself. Currently, my website consists of a header, navigation links, an image below the nav (to be updated later), and 3 content divs beneath that. ...

Steps for filling an HTML table within a dynamically loaded DIV

I have a container in my HTML page where I dynamically load other pages using the jQuery.load() function. One of the pages requires me to populate a table from the database just after/before it loads. How can I trigger a JavaScript function to execute righ ...

Having difficulty retrieving POST request information from an HTML form using Flask

I have been experimenting with building a website back-end using the Python library Flask. However, I keep encountering a 405 - Method not allowed error whenever I attempt to retrieve form data from a POST request in a secure manner. Right now, after a use ...

Check for length validation including spaces in JavaScript

My code includes a functionality that calculates the length of characters in a text area using both JSP and JavaScript: <textarea class="textAreaLarge" id="citation" rows="20" cols="180" name="citation" ...

Remove the array element if the value is blank

I have an array with different objects, and I need to efficiently delete the entries where the name is empty, similar to the first and third object in the example below: var myArray = [ { "Name": "", "Value": "" }, { "Name": "aaa", "Value": "bbb" ...

How to circumvent an email forwarder that removes attributes from an image tag and still track email opens?

While it may seem like an impossible task, I decided to give it a try. If the service I am utilizing removes the attributes of an image tag =>, is there a workaround available? I attempted inserting random unicode characters to disrupt the parser, but ...