Animation that slides in from the left using CSS styling

My current project involves creating a slideshow, and while it is mostly working fine, I am facing an issue with the animations. The animation for sliding out works perfectly, but the animation for sliding in from the left doesn't seem to be functioning as expected. Even though it is initially set at -100%, the left margin gets stuck at 0% without any animation.

Javascript:

var images = [
    'http://i.imgur.com/ByyUANz.png',
    'http://i.imgur.com/S5FfOOB.png',
    'http://i.imgur.com/EuefPdv.png',
    'http://i.imgur.com/Ucvm4pJ.png',
    'http://i.imgur.com/pK5WBHN.png',
    'http://i.imgur.com/nuOLVpy.png'
]

function slideShow(startAt){
    var holder = document.getElementById("currentImage");
    var img = document.createElement("img");
    img.src = images[startAt];
    holder.appendChild(img);
    nextPicture(startAt, img);
}

function nextPicture(current, currentElement){

    var holder = document.getElementById("currentImage");
    setTimeout(function(){
        currentElement.className = "translateLeft";
        current += 1;
        var img = document.createElement("img");
        img.src = images[current];
        img.style.marginLeft = "-100%";

        holder.appendChild(img);
        img.className = "translateIn";

        if (current == 5){
            current = -1;
            nextPicture(current, img);
        } else {
            nextPicture(current, img);
        }

    }, 5000)

}

slideShow(0);

CSS:

.translateLeft {  
    transition: 3s;
    margin-left: 100% !important;
}

.translateIn {

    transition: 3s;
    margin-left: 0% !important;
}

Answer №1

Check out this amazing solution that I found for you! Click here

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style type="text/css">
        html,
        body,
        img {
            position: absolute;
            top:0;
            left: 0;
            margin: 0;
            padding: 0;
            height: 100%;
            overflow-x: hidden;
        }

        #currentImage {
            height: 100%;
            width: 1920px;
        }
        .translateOrigin {
            transition: none;
            transform: translate3d(-100%, 0, 0) !important;
        }

        .translateLeft {
            transition: transform 3s;
            transform: translate3d(100%, 0, 0) !important;
        }

        .translateIn {
            transition: transform 3s;
            transform: translate3d(0, 0, 0) !important;
        }
    </style>
</head>
<body>
<div id="currentImage">
</div>
<div id="buttons">
</div>
<script type="text/javascript">
    var images = [
        'http://i.imgur.com/ByyUANz.png',
        'http://i.imgur.com/S5FfOOB.png',
        'http://i.imgur.com/EuefPdv.png',
        'http://i.imgur.com/Ucvm4pJ.png',
        'http://i.imgur.com/pK5WBHN.png',
        'http://i.imgur.com/nuOLVpy.png'
    ];
    var imageEle = [];
    var currImage = 0;
    var holder = document.getElementById("currentImage");

    function imagesPreload() {
        for (var i = 0; i < images.length; i++) {
            var img = new Image();
            img.src = images[i];
            img.className = "translateOrigin";
            holder.appendChild(img);
            imageEle.push(img);
        }
    }

    imagesPreload();

    document.onkeydown = function(event){
        if(event.keyCode === 13) {
            nextPicture();
        }
    };

    function slideShow(startAt) {
        var holder = document.getElementById("currentImage");
        imageEle[currImage].className = "translateIn";
        nextPicture();
    }

    function nextPicture() {
        setTimeout(function () {
            var img = imageEle[currImage];
            img.addEventListener("transitionend", transitionEnd, false);
            img.className = "translateLeft";

            if (currImage == 5) {
                currImage = 0;
            } else {
                currImage++;
            }
            imageEle[currImage].className = "translateIn";

            /* Reset the image to original position */
            function transitionEnd() {
                img.className = "translateOrigin";
                img.removeEventListener("transitionend", transitionEnd, false);
                nextPicture();
            }
        }, 5000)
    }
    slideShow(currImage);

</script>
</body>
</html>

Answer №2

If you want to create a stunning slideshow, my recommendation is to utilize the CSS transform property instead of relying on margin. The concept involves creating a placeholder element called currentImage with a position of relative, and then placing all images inside it with their position set to absolute. By default, all images will be translated outside of the placeholder element, and by adding or removing classes such as show and hide, you can control their visibility within the slideshow.

let images = [
  'http://i.imgur.com/ByyUANz.png',
  'http://i.imgur.com/S5FfOOB.png',
  'http://i.imgur.com/EuefPdv.png',
  'http://i.imgur.com/Ucvm4pJ.png',
  'http://i.imgur.com/pK5WBHN.png',
  'http://i.imgur.com/nuOLVpy.png'
];

// Select the holder
let holder = document.getElementById("currentImage");

// Create the image elements
images.forEach(function(url) {
  let img = document.createElement("img");
  img.src = url;
  holder.appendChild(img);
});

// Image counter
let counter = 0;

// Set interval for the slideshow
let slideshow = setInterval(function() {
  // Stop the slideshow when reaching the end of images
  if(counter === images.length) {
    clearInterval(slideshow);
    return;
  }
  
  // Get all images
  let nodes = holder.getElementsByTagName("img");
  
  // Hide previous image
  if(nodes[counter - 1]) {
  nodes[counter - 1].className = "hide";
  }
  // Show next image
  nodes[counter].className = "show";
  
  counter++;
}, 2500);
#currentImage {
  background: gray;
  width: 300px;
  height: 300px;
  margin: 0 auto;
  position: relative;
  overflow: hidden;
}

#currentImage img {
  width: 100%;
  position: absolute;
  transform: translateX(-110%);
  -webkit-transition: -webkit-transform 1.0s ease 0s;
  -moz-transition: -moz-transform 1.0s ease 0s;
  -o-transition: -o-transform 1.0s ease 0s;
  transition: transform 1.0s ease 0s;
}

#currentImage img.show {
  transform: translateX(0%);
}

#currentImage img.hide {
  transform: translateX(110%);
}
<div id="currentImage">
</div>

Answer №3

If you're looking to implement something similar, consider the following code:

// HTML
<div id="currentImage">
  <div class="window">
    <div class="image-list">
      <div>
        <img src="http://i.imgur.com/ByyUANz.png" />
      </div>
      <div>
        <img src="http://i.imgur.com/S5FfOOB.png" />
      </div>

      <div>
        <img src="http://i.imgur.com/EuefPdv.png" />
      </div>

      <div>
        <img src="http://i.imgur.com/Ucvm4pJ.png" />
      </div>

      <div>
         <img src="http://i.imgur.com/pK5WBHN.png" />
       </div>

      <div>
        <img src="http://i.imgur.com/nuOLVpy.png" />
      </div>

    </div>
  </div>
</div>

You can also add some CSS styling:

// CSS
img {
  height: 50px;
  width: 50px;
}

.window {
  position: absolute;
  height: 50px;
  width: 50px;
  border: 2px solid red;
  overflow: hidden;
}
div {
  display: inline-block;
}
.image-list {
  list-style-type: none;
  display: inline-block;
  padding-left: 0px;
  margin: 0px;
  width: 350px;
  animation: slidingli 30s; 
}

@keyframes slidingli {
  0% {
    transform: translateX(0px);
  }

  16% {
    transform: translateX(-50px);
  }

  32% {
    transform: translateX(-100px);
  }

  48% {
    transform: translateX(-150px);
  }

  64% {
    transform: translateX(-200px);
  }

  80% {
    transform: translateX(-250px);
  }

  100% {
    transform: translateX(-300px);
  }
}

Feel free to explore the provided JSFiddle link for a live demo. Additionally, there are numerous libraries available that offer similar functionalities such as Fotorama.

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

Enrollment of Vue components

After importing the component into the JavaScript file, I added it to the index.vue file as follows: import fmsSubUnitDetails from '../subunitDetails'; export default{ components: { fmsSubUnitDetails }, } Despite this, I am still encount ...

What is the best way to shade the background when a hyperlink is pressed?

I am currently working on customizing the navigation bar for my website. My navbar consists of five elements, and I want to make an element appear darker when it is clicked. Here's what I have attempted so far: Utilizing jQuery to modify the ac ...

Retrieving a single item from an array of objects with the help of body parser

I need assistance with sending an array of objects to a post route in my express app. Here is my form (written in ejs format): <form action="/archiveList/<%= list._id %>" method="POST"> <input type="hidden" name="list" value = <%= items ...

Utilize JavaScript to enclose every piece of text within single quotes in a span element

I have a tiny snippet of text: "some sample text" just a little more "additional text" I am trying to figure out how to wrap all the content between quotation marks in a span container, similar to what hilight.js does. I've been struggling to make it ...

Generate a new core element featuring the top 10 users

In my app, I have a function that sorts users in the mobile_user table based on their earned points and assigns them a rank. This function is triggered every time an http request is made. Now, what I want to achieve is creating a new root node called lead ...

A guide on using key arrows in JavaScript to navigate and focus on elements

When working on my HTML project, I have a list of elements that I want to be able to select using the arrow keys. I've included my code here for reference: [http://jsfiddle.net/T8S7c/] What I'm trying to achieve is when the arrow keys are press ...

Is there a way to incorporate the image that was uploaded from the server onto an HTML page without using the file extension?

$('#userInfoPhoto').html(function () { return '<img src="../uploads/' + thisUserObject.profileimage + '" alt = "userphoto" style="width:250px; height:250px"/>' }); This script is essential for rendering images on th ...

Guide on transferring JavaScript Objects from the Front End to Spring Boot Back-end and effectively processing and parsing them

After struggling with this issue repeatedly while developing my web apps, I've reached a breaking point and need some help. My frustration might come across as venting, but I'm genuinely stuck. The challenge I'm facing is sending key-value ...

`A brief disruption in loading the visual style of Google Maps`

Using the Ionic Framework, AngularJS, and Google Maps API, I encountered an irritating issue with my mobile app. Every time the map loads, there is a noticeable delay in loading the map style. This delay is particularly problematic as my map style converts ...

Buefy: Secure the header of the table in place while allowing the rows to scroll freely

How can I make the header of the table component stay fixed while allowing only the rows to scroll? ...

Incorporating additional value attributes without replacing the existing ones

Is there a way to add a value attribute through jQuery without removing the old attribute, similar to how addClass works? I have 7 input fields that are being typed in, and I need to combine them into one word and pass it to another input field. When I try ...

PHP code for displaying images on the same level

Is there a way to position images side by side in PHP? For example: image image image image. Currently, with the following code: print "</h2><br><a href='form.php'><img src=***.jpg width=100 height=100 /><br> ...

Complete the missing elements of a CSS grid layout

I'm currently working on creating a grid layout that aligns with this wireframe design: https://i.sstatic.net/AdsMX.png Here is the markup I have implemented so far: <div class="grid"> <div class="spanWidth"> <img src="https:// ...

impact on the shape of the region's map

Is it possible to add an effect like a border or opacity when hovering over an area in an image map? I've tried using classes and applying hover effects with borders or opacity, but nothing seems to work as expected. Here's my code: <img src= ...

Display the array in the Vue view section without using curly braces

I am trying to display the following array in the view section without braces and quotations. Currently, it is showing with exact array containing braces and quotations. Array ["WHATSAPP", "2G", "CLIQ"] Code <v-col cols=& ...

I'm having trouble grasping the concept of serving gzip-compressed JavaScript and CSS files

Why is it important to serve compressed JavaScript and CSS files? I understand that it reduces file size, but does the browser/webserver have to decompress them to read them? It's been mentioned that the webserver handles the compression. Does this me ...

How can HTML text be displayed based on certain JavaScript conditions?

By modifying the style of the text, I was able to implement basic functionality for validating correct answers. However, my main query is whether it is feasible to display a specific phrase upon achieving a perfect score. Upon analyzing the provided sample ...

The paragraph text should dynamically update upon clicking a button based on JavaScript code, however, the text remains unchanged despite attempts to modify it

I recently started learning JavaScript and wanted to update the content of a paragraph when a button is clicked. However, I encountered an issue where this functionality doesn't seem to work. <body> <p id="paragraph">Change Text on cl ...

Disrupting a Program Operation

We are utilizing the gauge Google Chart applet to visually track the failure rates of message transfers on a SOAP interface via AJAX. My goal is to make the page's background flash red and white when the failure rate reaches 50% or higher, and remain ...

Floating CSS drop menu with added bottom margin

I have created a simple dropdown CSS menu positioned in the footer with an upwards direction. You can view it here: http://jsfiddle.net/RmTpc/11/ My issue is that I want the opened menu to have some bottom margin from the main list item ("Items"). However ...