Continuous Div Carousel with Looping in jQuery

I have developed a basic carousel to cycle through a series of divs, but I am facing some issues. I want the carousel to loop continuously so that after reaching "slide 07," it goes back to "slide 01." Unlike using a carousel plugin, I prefer having an overhang where you can see a portion of the adjacent slides on either side when viewing a particular slide.
Check out my demonstration on jsFiddle here: http://jsfiddle.net/neal_fletcher/BBXnP/3/

HTML:

<div class="outerwrapper">
    <div class="innerwrapper">
        <div class="inner-slide">SLIDE 01</div>
        <div class="inner-slide">SLIDE 02</div>
        <div class="inner-slide">SLIDE 03</div>
        <div class="inner-slide">SLIDE 04</div>
        <div class="inner-slide">SLIDE 05</div>
        <div class="inner-slide">SLIDE 06</div>
        <div class="inner-slide">SLIDE 07</div>
    </div>
</div>

<div id="left">LEFT</div>
<div id="right">RIGHT</div>

jQuery:

$(function () {

    var animating = false,
        outerwrap = $(".outerwrapper");

    $("#right, #left").click(function () {
        if (animating) {
            return;
        }
        var dir = (this.id === "right") ? '+=' : '-=',
            width = $(".inner-slide").width();
        animating = true;
        outerwrap.animate({
            scrollLeft: dir + width
        }, 600, function () {
            animating = false;
        });
    });

});

In the end, I aim for the carousel to function similarly to the BBC homepage slider: , where you can view the next and previous sections below the current one.
I welcome any suggestions or recommendations!

Answer №1

Although not flawless, this can provide a general direction to follow. I have also segmented your code for better clarity.

The main concept is to duplicate the first 2 and last 2 items, then position them at opposite ends of the list.

Take a look

Setting up initial variables:

var animating = false,
    slideWidth = $('.inner-slide').width(),
    $wrapper = $('.outerwrapper'),
    slideIndex = 2,
    slideLen = $('.inner-slide').length,

Creating the basic structure:

    build = function() {
        $firstClone = $('.inner-slide').eq(0).clone();
        $secondClone = $('.inner-slide').eq(1).clone();
        $preLastClone = $('.inner-slide').eq(slideLen - 2).clone();
        $lastClone = $('.inner-slide').eq(slideLen - 1).clone();
        $wrapper.find('.innerwrapper').append($firstClone, $secondClone).prepend($preLastClone, $lastClone);
        $wrapper.animate({
            scrollLeft: '+=' + slideWidth * slideIndex + 'px'
        }, 0);
    },

Function for sliding the wrapper:

    slide = function(dir, speed) {
        if(!animating) {
            animating = true;
            dir == 'right' ? slideIndex++ : slideIndex--;
            slideIndex == slideLen - 1 ? slideIndex == 0 : '';

            if(slideIndex == 0 && dir == 'left') {
                //if the slide is at the beginning and moving left

                slideIndex = slideLen + 1;                
                $wrapper.animate({
                    scrollLeft: slideIndex * slideWidth + 'px'
                }, 0, function() {
                    animating = false;    
                });
                slideIndex--;

            } else if(slideIndex == slideLen + 2 && dir == 'right') {
                //if the slide is at the end and moving right

                slideIndex = 1;                
                $wrapper.animate({
                    scrollLeft: slideIndex * slideWidth + 'px'
                }, 0, function() {
                    animating = false;    
                });
                slideIndex++;

            }
            $wrapper.animate({
                scrollLeft: slideIndex * slideWidth + 'px'
            }, speed, function() {
                animating = false;    
            });
        }
    };

Implementation in action:

$(function() {
    build();
    $('#right, #left').on('click', function() {
        slide($(this).attr('id'), 600)
    });
});

There are likely more efficient methods, but this should get you started!

Answer №2

Perhaps you are already familiar with them, but it's worth checking out the .append() and .prepend() methods.

Check out this code snippet:

$('.container').append($('.inner-box').eq(0));

This line of code will move (not copy) the first box to the end of the "container" div. On the other hand, using:

$('.container').prepend($('.inner-box').eq(-1));

you can move the last box to the beginning.

Cheers!

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

I need to display 5 columns in a parent component, each with its own unique icon. How can I conditionally render them in a React component?

Creating a parent component to reuse multiple times can be very useful. In my case, I have included 5 different icons in each instance of the component, all taken from hero icons. I have set up an object with unique ids for each child component, but I am ...

The destroySlider() function of BxSlider fails to work due to either an undefined slider or a function that is not

I'm facing an issue with my carousel setup using bxslider. Here is the code snippet responsible for initializing the carousel: jQuery(document).ready(function() { var carouselWidth = 640; var carousel; var carousel_Config = { minSlides: 1, ...

Viewing an image from a local file on a web browser

I am currently working on a project where I want the user to be able to select a local image that will then be displayed on the page. As someone who is new to web development, I did a lot of research and found some helpful information on StackOverflow. I t ...

Updating visual appearance with button clicks and unclicks

Is there a way to dynamically update the button image while clicking on it? This is what I have tried: $('.gamebox_minimap_plus').click(function() { $(this).css("background-image","url('gfx/plus2.png')"); }); The image ch ...

Having issues with the functionality of the Previous/Next button in my table

I am facing a challenge with my table as I am trying to include previous/next button for users to navigate through it. However, the interaction doesn't seem to be functioning properly, and I suspect that I need to establish a connection between the bu ...

Utilizing Json data with Jquery for dynamically placing markers on Google Maps

Seeking assistance as I am currently facing a problem where I need to loop through JSON data and add it as markers on Google Maps, but unfortunately, it only returns null value. Is there a way to automatically connect this to JSON? My plan is to have a Gr ...

Incorporating JSON data into an array using d3

I'm currently working on mapping JSON data to an array variable in d3. Below is the JSON I am using: [ { "Impressions": "273909", "Clicks": "648", "CPM": 4.6388278388278, "Cost": 1266.4, "CPC": 1.9543209876543, "Campaign": "C ...

Utilizing Javascript to Extract Data from Twitter Json Files

Can someone provide assistance with parsing JSON feed text retrieved from Twitter? I am looking to access and apply style tags to elements like the link, created date, and other information. Any tips on how I can achieve this task successfully would be g ...

Mastering the art of chaining promises in Mongoose

I need help figuring out how to properly chain promises for a "find or create" functionality using mongodb/mongoose. So far, I've attempted the following: userSchema.statics.findByFacebookIdOrCreate = function(facebookId, name, email) { var self = ...

Issue with Angular dropdown menu not showing the initial option

I am trying to set up a drop-down menu with the first item in the list appearing after it has been sorted by 'name' using the code snippet below: <h2 class="presentation site is-input-header">Site</h2> <div class="modal-select-ele ...

What are some solutions for resolving differences in the display of pseudo elements between Macbooks and Windows desktops?

Greetings! I successfully converted an XD file to HTML and CSS code. I tested it on my Windows PC, but I haven't had the chance to test it on a Macbook yet. Details: I implemented a button with a pseudo element to show a right arrow on the right side ...

Guide to transferring a series of numerical data from a website to a server through an Ajax request

I'm facing an issue with my ajax implementation. I am trying to send an array of integers that are selected using checkboxes. The array is populated correctly, but when it is sent to the controller method, it becomes null. Here is the Ajax code snipp ...

While troubleshooting the app, I encountered an error that says: "The property 'answers' cannot be read as it is undefined."

Everything was going smoothly with my app until it suddenly crashed, displaying the error message "Cannot read property 'answers' of undefined". Let's take a look at the specific piece of code causing the issue: function mapStateToProps({ ...

Is it possible to access the Firebase user object beyond the confines of the Firebase function?

Despite successfully logging users into my application using Google Auth from Firebase, I am facing an issue where the User object does not display on the front end of my application (which utilizes Pug templates). How can I resolve this? The code snippet ...

I am currently attempting to generate a chart that displays information on countries utilizing the restcountries API. Despite being a beginner in this area, I have encountered some challenges and am seeking guidance

I'm struggling to display detailed information for each country separately. Whenever I try to loop through the data, all the contents end up getting merged into a single cell. What can I do to achieve the desired result? https://i.stack.imgur.com/dZS ...

Tips for stopping PHP echo from cutting off a JS string?

I encountered an issue with my code: <!DOCTYPE html> <html> <head> <title>Sign up page</title> <meta charset="UTF-8"/> </head> <body> <h1>Sign up page</h ...

Display numeric data when hovering over circles in the Google Maps API using Javascript

I recently implemented the Google Maps example code that displays a circle hovering over a city, with the size of the circle representing the population. I'm looking to enhance this feature by including numeric data display on mouseover as well. Any a ...

"Encountered an issue while serializing the user for session storage in Passport.js. Have you already implemented code for

I have recently started learning nodejs and I am currently working on creating a login system. I followed the code for serializing the user from the passport documentation and placed it in config/passport.js. However, I keep encountering the error "Failed ...

Quick way to include id="" and class="" attributes to HTML elements using Sublime Text 2

Is there a way to configure Sublime Text 2 where inputting a . (dot) automatically generates class=" " and adding a # (hash) creates id=" " while typing an HTML opening tag? ...

Although IE may have issues, @font-face is not functioning properly in Chrome and FireFox

Hello, I've encountered an issue with implementing @font-face in CSS. It seems to be working properly in Internet Explorer, but it has no effect in FireFox and Chrome. I am trying to add a custom font to my website by placing the files Snazanin.ttf an ...