Incorporate smooth transitioning effects with CSS onto the image carousel

My challenge involves creating a slider with 3 images and corresponding buttons that change the current image when clicked. I now seek to enhance this functionality by incorporating smooth transitions using CSS.

I envision a scenario where clicking on any bullet causes the current image to fade out, followed by the new image fading in. How can this be achieved?

var listItemContainer = document.getElementById('carousel-index');
var imageChanger = document.getElementById('image-container').getElementsByTagName('img');
var bulletNumber;

for (i = 0; i < listItemContainer.children.length; i++){
  (function(index){
     listItemContainer.children[i].onclick = function(){
     bulletNumber = index;
     imageChanger[0].setAttribute('src', 'https://civilian-interviewe.000webhostapp.com/img/mini_slider_' + (bulletNumber+1) + '.png');   
    }
  })(i);
};
body{
 text-align:center;
}
#carousel-index{
  margin:0;
  padding:0;  
}
#carousel-index li {
  display: inline-block;
  width: 2em;
  height: 2em;
  border-radius: 100%;
  background-color: #666;
  cursor: pointer;
}
<div id="image-container">
  <img src="https://civilian-interviewe.000webhostapp.com/img/mini_slider_1.png"/>
    <ul id="carousel-index">
      <li></li>
      <li></li>
      <li></li>
    </ul>
</div> 

Check out the CODEPEN for reference.

PD: Note that I aim to achieve this without relying on jQuery.

Answer №1

Check out this CodePen for a sample.

Included in the CSS are some transitions:

div#image-container {
opacity:1;
-webkit-transition: opacity 1s;
-moz-transition: opacity 1s;     
transition: opacity 1s; 
}

div#image-container.fade {
opacity:0;
}

Here is the function that manages the event:

var image = document.getElementById('image-container');
if(image.className === 'fade'){
    image.className = '';
    setTimeout(function(){
      image.className = 'fade';
    },1000)
  }else{
    image.className = 'fade';
    setTimeout(function(){
      image.className = '';
    },1000)
  }
setTimeout(function(){
    bulletNumber = index;
   imageChanger[0].setAttribute('src', 'https://civilian-interviewe.000webhostapp.com/img/mini_slider_' + (bulletNumber+1) + '.png');   
},1000);

Answer №2

Implement CSS3 animations by adding a class using JavaScript

var listItemContainer = document.getElementById('carousel-index');
var imageChanger = document.getElementById('image-container').getElementsByTagName('img');
var bulletNumber;

for (i = 0; i < listItemContainer.children.length; i++) {
  (function(index) {
    listItemContainer.children[i].onclick = function() {
      bulletNumber = index;

         imageChanger[0].className = "hide"; 
      
      setTimeout(function(){ 
          imageChanger[0].setAttribute('src', 'https://civilian-interviewe.000webhostapp.com/img/mini_slider_' + (bulletNumber + 1) + '.png');
         },501);
       
      setTimeout(function(){ 
     imageChanger[0].className = "show";
      }, 1001);
      
    }
  })(i);
};
body {
  text-align: center;
}
#carousel-index {
  margin: 0;
  padding: 0;
}
#carousel-index li {
  display: inline-block;
  width: 2em;
  height: 2em;
  border-radius: 100%;
  background-color: #666;
  cursor: pointer;
}

#image-container img.show  {
    animation: show .5s;
    animation-fill-mode: both;
}
@keyframes show {
    from {
        transform:scale(0.7);
        opacity:0
    }
    to {
        transform: scale(1);
        opacity:1
    }
}

#image-container img.hide  {
    animation: hide .5s;
    animation-fill-mode: both;
}
@keyframes hide {
    from {
        transform:scale(1);
        opacity:1
    }
    to {
        transform:scale(0.7);
        opacity:0
    }
}
<div id="image-container">
  <img src="https://civilian-interviewe.000webhostapp.com/img/mini_slider_1.png" />
  <ul id="carousel-index">
    <li></li>
    <li></li>
    <li></li>
  </ul>
</div>

Answer №3

If you are looking to achieve a fade effect using CSS transitions, setting the opacity property is key.

var listItemContainer = document.getElementById('carousel-index');
var imageChanger = document.getElementById('image-container').getElementsByTagName('img');
var bulletNumber;
imageChanger[0].classList.add('fadeIn');
for (i = 0; i < listItemContainer.children.length; i++){
  (function(index){
     listItemContainer.children[i].onclick = function(){
     bulletNumber = index;
   imageChanger[0].classList.remove('fadeIn');
   
     setTimeout(function(){ 
   
     imageChanger[0].classList.add('fadeIn');
     } , 100);
     imageChanger[0].setAttribute('src', 'https://civilian-interviewe.000webhostapp.com/img/mini_slider_' + (bulletNumber+1) + '.png');   
      
 
    }
  })(i);
};
body{
 text-align:center;
}
#carousel-index{
  margin:0;
  padding:0;  
}
#carousel-index li {
  display: inline-block;
  width: 2em;
  height: 2em;
  border-radius: 100%;
  background-color: #666;
  cursor: pointer;
}
img {
  opacity:0;
}
img.fadeIn {
  opacity:1;
  transition:opacity 0.5s ease;
}
<div id="image-container">
  <img src="https://civilian-interviewe.000webhostapp.com/img/mini_slider_1.png"/>
    <ul id="carousel-index">
      <li></li>
      <li></li>
      <li></li>
    </ul>
</div> 

The starting opacity for the image should be set to 0:

img {
  opacity:0;
}
img.fadeIn {
  opacity:1;
  transition:opacity 0.5s ease;
}

On click, remove the added class to reset the opacity to 0, then add it again. Adjusting timing values can help achieve the desired effect.

UPDATE: To incorporate fadeIn and fadeOut effects properly with a container and image source changing, an additional timeout is needed:

var listItemContainer = document.getElementById('carousel-index');
var imageChanger = document.getElementById('image-container').getElementsByTagName('img');
var bulletNumber;
imageChanger[0].classList.add('fadeIn');
for (i = 0; i < listItemContainer.children.length; i++){
  (function(index){
     listItemContainer.children[i].onclick = function(){
     bulletNumber = index;
   imageChanger[0].classList.remove('fadeIn');
   imageChanger[0].classList.add('fadeOut');
   
     setTimeout(function(){ 
   
     imageChanger[0].classList.add('fadeIn');
     imageChanger[0].classList.remove('fadeOut');
     } , 1000);
       setTimeout(function(){ 
     imageChanger[0].setAttribute('src', 'https://civilian-interviewe.000webhostapp.com/img/mini_slider_' + (bulletNumber+1) + '.png');   
      } , 1000);
 
    }
  })(i);
};
body{
 text-align:center;
}
#carousel-index{
  margin:0;
  padding:0;  
}
#carousel-index li {
  display: inline-block;
  width: 2em;
  height: 2em;
  border-radius: 100%;
  background-color: #666;
  cursor: pointer;
}
img {
  opacity:0;
}
img.fadeIn {
  opacity:1;
  transition:opacity 0.5s ease;
}
img.fadeOut {
  opacity:0;
  transition:opacity 0.5s ease;
}
<div id="image-container">
  <img src="https://civilian-interviewe.000webhostapp.com/img/mini_slider_1.png"/>
    <ul id="carousel-index">
      <li></li>
      <li></li>
      <li></li>
    </ul>
</div> 

P.S. It's recommended to preload images for smooth functionality on initial load.

Answer №4

Here is a JS-based alternative solution that does not require changes to HTML or CSS (explanation provided as comments in the code):

var listItemContainer = document.getElementById('carousel-index');
var imageChanger = document.getElementById('image-container').getElementsByTagName('img')[0];
var newSrc, fadeDelta=-0.01; //adjust 'fadeoutDelay' and 'fadeinDelay', do not modify 'delta'

(function initImageChanger(i,count){
  imageChanger.style.opacity = 1; //set opacity using JavaScript to avoid empty value
  listItemContainer.children[i].onclick = function(){
    var fadeoutDelay=5, fadeinDelay=15, opacity=parseFloat(imageChanger.style.opacity); //modify delays for different fade speeds
    
    function changeSrc(){
      var src = imageChanger.getAttribute('src');
      var ext = src.substring(src.lastIndexOf('.')); //store extension
      src = src.substring(0,src.lastIndexOf('_')+1); //store source up to identifying number
      return src+i+ext; //combine parts into full source
    }
    function fade(delay){
      imageChanger.style.opacity = (opacity+=fadeDelta);
      if (fadeDelta<0 && opacity<=0){ //fade-out complete
        imageChanger.setAttribute('src',newSrc);
        fadeDelta*=-1, delay=fadeinDelay; //reverse fade direction
      } else if (fadeDelta>0 && opacity>=1){newSrc=null, fadeDelta*=-1; return;} //fade-in complete, stop function
      setTimeout(function(){fade(delay);},delay);
    }
    //initiate fade only if image is not already fading, otherwise just change source (and reset)
    if (changeSrc() != imageChanger.getAttribute('src')){
      newSrc=changeSrc();
      if (opacity==0 || opacity==1){fade(fadeoutDelay);}
      else if (fadeDelta>0){fadeDelta *= -1;} //reset fade for new source
    }
  };
  if (++i < count){initImageChanger(i,count);} //move to next element
})(0,listItemContainer.children.length); //provide starting arguments
body {text-align:center;}

#image-container img {width:auto; height:150px;}
#carousel-index {margin:0; padding:0;}
#carousel-index li {display:inline-block; width:2em; height:2em; border-radius:100%; background-color:#666; cursor:pointer;}
<div id="image-container">
  <img src="https://civilian-interviewe.000webhostapp.com/img/mini_slider_1.png"/>
  <ul id="carousel-index"><li></li><li></li><li></li></ul>
</div>
Check out the codepen example: http://codepen.io/anon/pen/xgwBre?editors=0010

Answer №5

Here's a non-jQuery solution that may not be perfect, but gets the job done:

Start by creating a new function:

function fadeChange(element) {
    var op = 0.1;
    var timer = setInterval(function () {
        if (op >= 1){
            clearInterval(timer);
        }
        element.style.opacity = op;
        element.style.filter = 'alpha(opacity=' + op * 100 + ")";
        op += op * 0.1;
    }, 10);
}

Then invoke that function when setting the new image:

fadeChange(imageChanger[0]);

This method can be seen in action on this codepen link.

While a little clunky, it effectively fades the images. For smoother transitions, you might consider using a single image for the monitor and updating only its content using this approach.

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

Replacing values in an HTML file with MySql query results

----- Problem solved, solution below ----- In my HTML file, I have a dropdown menu for various courses listed as follows: <ul> <li class="dropbtn" id="1"> <a href="">first</a> <ul class="dropdown-content"> ...

Switch up the position of an element every time the page is refreshed

I have a webpage containing 5 images, each measuring 48px by 48px. I would like these images to be displayed in random positions on the page every time it is loaded. While I am aware that I will need to use CSS and JavaScript for this task (specifically f ...

Detecting collisions on a pixel-by-pixel basis within Javascript/Jquery/Gamequery

Currently, I am working on developing a web game using Jquery with the GameQuery plugin. However, I have encountered an issue where the GameQuery plugin does not support per pixel collision detection, only bounding boxes collision detection. Is there a way ...

Is it time to ditch Internet Explorer for EDGE?

Have you ever noticed that when attempting to access the stackoverflow website on Internet Explorer, the tab mysteriously closes and Microsoft Edge opens with stackoverflow loaded? What is the secret behind this strange phenomenon on stackoverflow's ...

What is the best way to retrieve a JSON element obtained from a Parse.com query?

I'm encountering difficulties when attempting to access a specific JSON element that I receive in response from a query made into a Parse.com Class. Despite reading through various questions and answers on similar topics, I have yet to find a solutio ...

Perform the same actions on every element within the ul li

I'm facing an issue with my unordered list, where each list item contains a span element with an image inside. My goal is to set the background-image of each span to be the same as the image it contains, while also setting the opacity of the image to ...

Resolving Issues with Page Feature Images on Your WordPress Site

Currently enrolled in a web development course, I collaborated with my instructor to create a custom website. However, I am facing an issue where the header image appears shorter on the Resources page () and Contact page () compared to the Blog page (). De ...

Troubles arise when utilizing getChannelData to configure socket.io in web audio,

I'm facing a problem where my connection gets disconnected as soon as I execute the code source.buffer.getChannelData(0).set(audio);. This issue occurs when I transcode an audio file and send the audio buffer to the client using socket.io for playback ...

Obtain the selected dropdown value and transfer it to the controller seamlessly without the need to reload the page

Currently, I am facing an issue with two dropdown lists in a bootstrap modal - CATEGORY and SUBCATEGORY. The values in the SUBCATEGORY list depend on the selection made in the CATEGORY list. My goal is to retrieve the selected value ID and pass it to my co ...

Manipulating data with Angular's array object

I am having an issue with posting an object array. I anticipate the post to be in JSON format like this: {"campaign":"ben", "slots":[ { "base_image": "base64 code here" } ] } However, when I attempt to post ...

Managing the scrolling direction horizontally with waypoints.js

As I work on creating a custom wizard form with waypoints, I've encountered an interesting issue that has left me puzzled. In my sample CODEPEN, you can see two pages of the wizard process to better understand the problem. Upon clicking the forward ...

Error: Invalid syntax detected: /blog

I am encountering an issue with jQuery while trying to add a blog section to my existing single-page site. The new blog will be located in a separate /blog directory, causing the menu item for it to differ from the other href="#" tags on the index.html pag ...

In what ways can you toggle the visibility of table rows and data dynamically with the onchange event in HTML?

I'm dealing with an HTML code that can dynamically change table data based on user selection. Here's the snippet of my HTML code: Select an option: <select name='set' id="set" class="selectpicker" onchange='displayFields(this. ...

`Is there a tutorial on parsing HTML with nested tags using Simple DOM Parser?`

I am currently working on parsing an HTML file that contains several DIV elements structured like this: <div class="doc-overview"> <h2>Description</h2> <div id="doc-description-container" class="" style="max-height: 605px;"> <di ...

I am having trouble with my jquery.ajax configuration where the async parameter is set to true. The data is not being sent back to

My goal is to save content whenever a button or hyperlink is clicked using jquery.ajax in an Asp.net 3.5 environment. Here is the logic I am following: I use .bind in jquery to attach my custom method(MakeLog) to a button click or hyperlink click. Sinc ...

Identifying text within clicked divs using identical ids

$(document).ready(function(){ $('#peoplelayer').click(function(){ $(this).fadeOut(500); var str = $(this).text(); alert(str); }); }); This is code where I use the same id "#peoplelayer" for all the divs. When on ...

Step-by-step guide on how to import the socket.io npm package in Node.js

let socket = new Server(); import Server from 'socket.io'; Error: Module 'socket.io' does not have a default export ...

Performing a JavaScript AJAX request to send a complex object containing an array of other complex objects within it

My issue arises from encountering an empty array of objects at the backend. To illustrate, I have established two classes at the backend... public class ScoreModel { public string Subject { get; set; } public float Score { get; set; } ...

Add HTML code into a contenteditable element and then include additional text following the inserted HTML

I'm working with a contenteditable div and a button that inserts a simple span. <button id="insert-span">Insert</button> <div id="edit-box" contenteditable="true"></div> <script> $('#insert-span').on(' ...

Unable to retrieve responseText from AJAX call using XrayWrapper

I am utilizing the IUI framework and attempting to retrieve the results from an ajax call. When inspecting the call in Firebug, it shows an "XrayWrapper[Object XMLHttpRequest{}", but I am struggling to access the responseText from the object. Upon expand ...