Move the divs within the overflow container by sliding them, then take out the initial element and append it to the end

Currently, when I utilize .appendTo(".wrapper") as shown in the code below, it eliminates the animation effect. My goal is to have the div on the far left slide out of view, triggering an overflow hidden effect, and then be placed at the end of the slide creating a continuous slideshow effect by repeating the previous divs.

   $(document).ready( function(){
        var x = 0;
        $(".next").on("click", function(){
            x -= 245;
            console.log($(".element").length)
            $(".element").each(function(i, e){
                console.log(i)
                $(this).eq(i).css({"marginLeft" : x +"px"}).appendTo(".wrapper");
            })
        })
    });

CSS:

    .mgcont{
        margin:5% auto;
        width:970px;
        overflow: hidden;
        border: 2px solid gray;
    }
    .wrapper{
        /*overflow: hidden;*/
        white-space: nowrap;
        width:960px;
    }
    .element{
        width: 240px;
        height: 300px;
        background: tomato;
        display: inline-block;
        margin-left: 10px;
        transition: margin 3s;
    }
    .prev{
        float: right;
    }

HTML:

<div class="mgcont">
    <button class="next">next</button>
    <button class="prev">PREV</button>
    <div class="wrapper">
        <div class="element">1</div>
        <div class="element">2</div>
        <div class="element">3</div>
        <div class="element">4</div>
        <div class="element">5</div>
        <div class="element">6</div>
    </div>
</div>

FIDDLE

Answer №1

To make adjustments to your JavaScript code, follow these steps:

        $(document).ready( function(){
        $(".next").on("click", function(){
            console.log($(".element").length)
            $(".element").each(function(i, e){
                console.log(i)
            })
                $(".element").eq(0).css({"margin-left" : "-245px"}).delay(3000).queue(function(next){
                    $(this).appendTo(".wrapper").css({"margin-left":"10px"});
$( this ).dequeue();
});
        });
    });

Don't forget to update the CSS for the transition property as well:

.element{
        width: 240px;
        height: 300px;
        background: tomato;
        display: inline-block;
        margin-left: 10px;
        transition: margin-left 3s;
    }

These changes should work flawlessly for your project.

Check out the updated Fiddle here

If you prefer using a separate CSS class, implement these modifications:

$(document).ready( function(){
        $(".next").on("click", function(){
            console.log($(".element").length)
            $(".element").each(function(i, e){
                console.log(i)
            })
                $(".element").eq(0).addClass('translateleft').delay(3000).queue(function(next){$(this).appendTo(".wrapper").removeClass('translateleft');
$( this ).dequeue();
});
        });
    });

In your CSS file, define styles for the translateleft class like this:

   .translateleft{
    animation: translateleft 3s;
    -webkit-animation:translateleft 3s;
    -moz-animation:translateleft 3s;
    -o-animation:translateleft 3s;
}
@keyframes translateleft{
    from{margin-left:0px;}
    to{margin-left:-245px;}
}
@-webkit-keyframes translateleft{
    from{margin-left:0px;}
    to{margin-left:-245px;}
}
@-moz-keyframes translateleft{
    from{margin-left:0px;}
    to{margin-left:-245px;}
}
@-o-keyframes translateleft{
    from{margin-left:0px;}
    to{margin-left:-245px;}
}

For a demonstration, see the working example in this Fiddle link

UPDATE The .dequeue() statement was omitted from the function. The answer has been revised and now functions correctly for repetitions.

Answer №2

I have made changes to all the files. You can test the code snippets below:

   $(function(){
  var width = $('.element:first').width();   
$(".next").on("click", function(){
    var neww = $(".element:first").clone();
    $('.element').eq(1).css({'margin-left':'-'+width+'px'});
     $(".element:first").remove();
    neww.appendTo('.wrapper');        
   $('.element:last').css({'margin-left':'5px'});
});
$(".prev").on("click", function(){
    var neww = $('.element:last').clone();
    $(".element:last").remove();
     $('.element:first').css({'margin-left':'5px'});
    neww.prependTo('.wrapper');
    $('.element:first').css({'margin-left':'-'+width+'px'});
});
 });
   .mgcont{
    margin:5% auto;
    width:970px;
    overflow: hidden;
    border: 2px solid gray;
}
.wrapper{
    /*overflow: hidden;*/

    white-space: nowrap;
    width:960px;

}
.element:first-child{
    margin-left: -240px;
}
.element{
    width: 240px;
    height: 300px;
    background: tomato;
    display: inline-block;
    margin-left: 5px;
    transition: all 3s;
}
.prev{
    float: right;
}
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
   <div class="mgcont">
<button class="next">next</button>
<button class="prev">PREV</button>
<div class="wrapper">
  <div class="element">6</div>
  <div class="element">1</div>
  <div class="element">2</div>
  <div class="element">3</div>
  <div class="element">4</div>
  <div class="element">5</div>      
</div>
  </div>

Feel free to give it a try and let me know if it meets your expectations.

Check out the DEMO for a working example.

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 array functions properly when handwritten, but fails to work when loaded from a text file

I have been developing a password recommendation script that aims to notify users when they are using a commonly used password. In order to achieve this, I decided to load the list of common passwords from an external text file. However, it seems that the ...

Select the date that is three months from now using the datetimepicker feature of Bootstrap

I have two datetimepicker fields for selecting a start date and end date. I am utilizing the eonasdan datetimepicker plugin for Bootstrap. I am trying to set the range from the current date up to 3 months ahead. However, when I use maxdate:'+90d&apo ...

working with a list of Python objects in a JavaScript environment

Currently, I am building a web application using Flask and Python. In my Python code, I have a class that can be parsed as JSON. class uItem: itemCount = 0 def __init__(self, id, name): self.id = id self.name = name I am trying to acce ...

I tried to use my Google Maps app, but for some reason, it failed

Here's the code snippet I've been working on: if($_POST){ // get latitude, longitude and formatted address $data_arr = geocode($_POST['address']); // if able to geocode the address if($data_arr){ $latitude = $data_arr[0]; $l ...

Navigating Form Submission in Next.js

In this code snippet, I attempted to perform simple addition (ket=name + names). The desired outcome is a numerical sum displayed as “ket”. However, when entering 3 and 6 into the input fields, the result appears as 36 instead of 9. export default fu ...

"Enhance your website with a Bootstrap container for sharing

I'm currently working on an app that creates a URL that needs to be shared. I'm looking for the perfect container to use with bootstrap 4 to display this generated URL. My goal is to have it resemble the functionality of a Google Drive shareable ...

Utilize Restangular to send data as a payload rather than a query string

Currently, my backend service is set up to register a new user in our system using the following URL: /api/users/register When using Restangular, post requests are typically sent as either query string: Restangular.all('users').post("register" ...

Retrieve the specific key or object number by conducting a search in JavaScript

I am faced with the challenge of editing a large XML file by searching for a specific keyword within the "event name" field and changing the corresponding "active" value to either 1 or 0. The structure of the data file is as follows. I have managed to modi ...

Unable to modify div style using a JS function

I am attempting to show different divs based on the button clicked, with all starting with a display style of "none" except for one default div called "atualizacoes". After clicking a button, all divs should be set to display="none", and then the specific ...

Is there a way to detect the completion of the fadeout animation before calling a function?

I am trying to create a toast message using jQuery. When the "show" class is appended to the div, I want the toast message to fade in and then fade out after a few seconds. Once the fade-out animation is complete, I need to remove the "show" class. This ...

Having difficulty choosing a drop-down menu option with AJAX technology

My current project involves creating a page where the database is updated upon a drag-and-drop event. Specifically, I have implemented drag-and-drop functionality on a page, and whenever a div (deal-card) is dragged and dropped into another div (stage-colu ...

Customized settings saved in local storage using JavaScript

Here is the script I am currently using for my app: <script> if (localStorage.getItem("0") === null) { //do nothing } else if(localStorage.getItem("1")===null{ } else if(localStorage.getItem("2")===null{ } else if(localStorage.getItem("3")===null ...

React 16 is encountering a discrepancy due to the absence of the data-reactroot attribute

As I was in the midst of updating some apps to React 16, I couldn't help but notice that the data-reactroot attribute is no longer present on the main root element. Although not a critical issue, it seems like we had certain code and styles that reli ...

Delete a div when a button is clicked through JavaScript

I'm having an issue with a form I created that duplicates itself - I can't seem to get the 'x' button to remove the corresponding div as needed. I have placed both buttons outside of the div like this: <button type="button" id="cro ...

I am puzzled as to why my code in React is rendering twice without any apparent reason

I ran into a strange issue where my console.log("hi") was being displayed twice. I was working on a simple todo-list project and noticed that everything was getting double clicked. After some troubleshooting, it seems like the code is executing any JavaScr ...

Is there a way to simulate Pinia and vue-i18n simultaneously?

Exploring Vue 3's Composition API with a twist: The store.ts file import { ref, Ref } from 'vue'; import { defineStore } from 'pinia'; export const useStore = defineStore('store', () => { const isLoading: Ref<bo ...

Next JS throwing internal server error when authenticating with axios

I'm encountering a 500 internal server error when trying to authenticate with Next Auth. I followed the documentation from Next Auth for implementation. import NextAuth from "next-auth"; import CredentialsProvider from "next-auth/provi ...

Retrieving CSS style values with Node.js

I am looking to design a new CSS style that includes the lowest and highest values. table[my-type="myStyle"] { width: 255.388px !important; } This code snippet is included in numerous CSS files within my style directory. ...

SwipeJS experiencing technical difficulties

My Swipe.Js version : "^7.0.2" Today, I attempted to use Swipe.Js and encountered an issue with my import code. import { Swiper, SwiperSlide } from 'swiper/react'; as described on https://swiperjs.com/react#installation. However, when ...

Tips for eliminating the gap between Bootstrap 4 columns

Is there a way to eliminate the spacing between Bootstrap columns? I have three columns set up using Bootstrap but no matter what I do, I can't seem to get rid of the space between them. <!doctype html> <html lang="en> <head> ...