Personalized jQuery Slider, Go back to initial slide

Working on enhancing my jQuery skills by constructing a basic slider with 3 slides. The slider wrapper, with a fixed width of 1400px and a height of 350px serves as the outer container.

Within this wrapper lies an unordered list where its items are floated left to enable them to be displayed in a horizontal arrangement. This entire unordered list is then animated to shift to the left by 1400px, creating the sliding effect. I am currently facing a challenge determining how to smoothly return to the initial slide without any abrupt transitions. Below is the HTML snippet:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>Untitled Page</title>
     <script type="text/javascript" src="jquery-1.11.1.js"></script>
    <script type="text/javascript" src="slider.js"></script>
        <style>
            * { margin: 0; padding: 0; }
            #sliderwrapper { width: 1400px; height: 350px; overflow: hidden; position:relative;}
            #sliderlist  { list-style: none; left: 0px; position:absolute; width:200000em;}
            .item { float: left; }

        </style>
    </head>


<body>

    <div id="sliderwrapper">

        <ul id="sliderlist">
            <li class="item 1">
                <div><img src="img1.png" /></div>
            </li>
            <li class="item 2">
                <div><img src="img2.png" /></div>
            </li>
            <li class="item 3">
                <div><img src="img3.png" /></div>
            </li>
        </ul>

    </div>

</body>
</html>

And here is my implementation using jQuery:

$(document).ready(function () {


    setInterval(slide, 1000);

    function slide() {

        var left = $('#sliderlist').css('left');
        left = left.substring(0, left.length - 2);
        if (left <= -2800) {

            /*var slide = $('#sliderlist li:first');
            $('#sliderlist').children('li:first').remove();
            $('#sliderlist').append(slide);*/

            $('#sliderlist').css('left', '0px');
            $('#sliderlist').animate({ left: "-=1400" }, "slow", "swing");
        }
        else {
            $('#sliderlist').animate({ left: "-=1400" }, "slow", "swing");


        }
    }

});

Every second, the slide function is triggered, animating the list to the left. Upon reaching the last slide (-2800px), it's crucial for the first slide to reappear seamlessly instead of suddenly popping up. Trying different solutions like setting the left property to 0px or constantly removing and appending items resulted in a jarring animation.

Answer №1

How about incorporating a smooth animation to reset it back to 0 while sliding through your slides with animated transitions? Take this code snippet for example:

if (left <= -800) {
    $('#sliderlist').animate({
        left: "0px"
    }, "slow", "swing");
} else {
    $('#sliderlist').animate({
        left: "-=400"
    }, "slow", "swing");
}

Adding an animation from the last slide to the first slide creates a seamless transition which is commonly seen in many jQuery sliders.

Answer №2

I came across a solution that worked for me. Here is the code snippet:

http://jsfiddle.net/f6rey710/1/

function slide() {

        var left = $('#sliderList').css('left');
        left = left.substring(0, left.length - 2);
        if (left <= -800) {


            $('#sliderList').css('left', '-400px');
            var slide = $('#sliderList li:first');
            $('#sliderList').children('li:first').remove();
            $('#sliderList').append(slide);
            $('#sliderList').animate({ left: "-=400px" }, "slow", "swing");

        }
        else {
            $('#sliderList').animate({ left: "-=400" }, "slow", "swing");
        }
    }

When the slide function reaches the end of the list, elements are removed from the front and added to the end.

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

When utilizing Next.js, the router.push feature will automatically scroll the page to the top, even if the scroll option

Incorporating Next.js' built-in internationalisation features allowed me to seamlessly switch my app's language, but there is one specific issue I'm encountering: When I trigger the changeLanguage function, it causes the page to scroll back ...

Updating the key within an array of objects

In my array of objects, I have the following data: arrayOfObject = [{'key1': [1,2]} , {'key2': [1,2,3]} , {'key3': [1,2,4]}] I know the name of the key that I want to replace in my array : var keyString = 'key1&apos ...

Utilize a single JavaScript script to handle numerous HTML forms within the same webpage

I am currently facing an issue with a page that contains multiple forms needing the same JavaScript code. This specific code is designed to add more input fields to the form, which it does successfully. However, the problem lies in the fact that it adds in ...

Pause and anticipate the completion of a page loading before utilizing Angular functionality

I am currently using a MEAN stack in my program that looks something like this: view: <div class="container" data-ng-controller="HomeController"> <div class="swiper-wrapper"> <div class="swiper-slide" ng-repeat="player in d ...

Sending an array of JSON data to an MVC controller property for model binding

I need assistance with passing an integer array using jQuery Ajax. It seems like my controller is not receiving the data properly. Here is the jQuery AJAX call: var box = {MECallButtons: R_MainEntranceButtons } $.ajax({ type: "POST", url: "/Home ...

Save the output of Html.Raw() into a JavaScript variable when using ASP.NET MVC 3

One issue I'm encountering in my ASP.NET project involves retrieving a string of HTML from the database and assigning it to a client-side variable. Currently, I am using the following code: var x = '@Html.Raw(myModel.FishValue)' This work ...

Delete the event handler if the original selector used to set up the handler is unknown

I need to remove an event handler from the element. The current handler is added by a third-party plugin, and I want to prevent its behavior. As far as I know, the functions off() and unbind() require the original selector to be used. The issue arises b ...

I could really use some guidance on how to begin with the Node.JS app file in BlueMix

After delving into JS tutorials, I feel comfortable with the syntax and approach. Now, my focus is on utilizing Node.JS to develop an app using BlueMix. While I consider myself proficient in Java, web programming is uncharted territory for me, leaving me s ...

Allocating the remaining container space to a lone flex item

Imagine a scenario where I have a flex container with children that completely fill the container. .container { display: flex; width: 150px; } .item { flex: 1 1 50px; border: 1px solid blue; } <div class="container"> <div class="item ...

Is it possible to write CSS 3 rows without using the :not() selector for improved efficiency?

Consider using CSS code like the following in some cases: input:not([type="submit"]):not([type="checkbox"]):not([type="radio"]):not([type="file"]) { border:1px solid #fff; background-color:#f3f4f5; } <div><input type="text" name="alpha" /&g ...

What causes insertMany in mongoose to not generate ObjectIds?

Currently, I am in the process of developing an application using Node.JS and MongoDB. My challenge lies in inserting multiple documents with predefined _ids and some ObjectId arrays. When I utilize insertMany function, all document _id fields turn into st ...

Click event not functioning correctly in Internet Explorer

When using jQuery, I have the following code: <script type="text/javascript"> $(document).ready(function(){ $('body').on('click', '.add-photo',function() { $("#images").append($('<input/>').attr(&apo ...

What's more efficient in terms of performance, checking for a class versus adding a class?

When dealing with a function that triggers on a scroll event, which method is more efficient? Checking if a class is already added and adding it if not Simply adding the class without any checks each time $(document).on('scroll', function ( ...

Enhancing AngularJS functionality through the integration of jQuery within a TypeScript module

As I try to integrate TypeScript into my codebase, a challenge arises. It seems that when loading jQuery and AngularJS in sequence, AngularJS can inherit functionalities from jQuery. However, when locally importing them in a module, AngularJS fails to exte ...

Hexagonal design reminiscent of a beehive

I am struggling with implementing a specific layout using grid CSS and I'm open to using flex or any other method. .container { display: grid; grid-template-columns: repeat(auto-fit, 50px); grid-template-rows: repeat(auto-fit, minmax(80px, 80px)); ...

Sending the axios fetched property from the parent component to the child component results in the error message "TypeError: Cannot read property 'x' of undefined"

I've noticed that this question has been asked before, but none of the solutions provided seem to work for my situation. Parent component import axios from "axios"; import { useEffect, useState } from "react"; import Child from &q ...

"Using JavaScript to Make Requests on Mobile Devices via HTTP

Greetings everyone, I have a query regarding implementing an endpoint api in my mobile application. For instance, suppose I have a server handling data and I want to notify my mobile application about new updates by sending a post request. Is this feasibl ...

Why does variable passing use 'object Text' instead of passing values?

In my for loop, I am dynamically creating a table with radio buttons and trying to create labels dynamically as well. However, when I pass the variable to the label text node, it prints out 'object Text' on the page instead of the expected value. ...

Troubleshooting Issue with Jssor Slider in Internet Explorer 11 due to Relative Dimensions

Encountering an issue with the relative dimensions of the slider container in IE11 (Jssor 18.0). Here is the HTML structure: An outer div with specified absolute dimensions (width and height in pixels). An inner div, serving as the slider's contain ...

What is the best way to style the header of a table when scrolling in CSS?

Currently, I am facing an issue with applying the top CSS property to the thead element of a table while scrolling. I have attempted various methods but have been unsuccessful in achieving the desired outcome. Initially, I used the scroll event, however, ...