Creating a loop in a column-based carousel without using JavaScript

I'm currently working on developing a carousel using JavaScript or jQuery. I've attempted the code snippet below, but I'm having trouble getting it to display in 3 or 4 columns. While I understand that Bootstrap can handle this easily, I'd like to achieve it without relying on a Bootstrap plugin. The carousel itself is functional, but the looping feature isn't working as intended.

var container = $("#carousel_wrapper");
    
    var runner = container.find('ul');
    var liWidth = runner.find('li:first').outerWidth();
    var itemsPerPage = 3;
    var noofitems = runner.find('li').length;
    
    runner.width(noofitems * liWidth);
    container.width(itemsPerPage*liWidth);

    $('#right').click(function() {
        $(runner).animate({ "left": "-=51px" }, "slow" );
    });
    
    
    $('#left').click(function() {
        $(runner).animate({ "left": "+=51px" }, "slow" );
    });
div#carousel_wrapper{

    overflow:hidden;
    position:relative;
    width:500px;
    height: 100px;
}

ul {
    padding:0px;
    margin:0px;
    position: absolute;
    top:50px;
    left: 0px;
    width:300px;
    height: 50px;
    overflow: hidden;
}
ul li {
    list-style:none;
    float:left;
}
ul li div {
    border:1px solid white;
    width:50px;
    height:50px;
    background-color:gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="carousel_wrapper">
    <ul>
        <li>
            <div>0</div>
        </li>
        <li>
            <div>1</div>
        </li>
        <li>
            <div>2</div>
        </li>
        <li>
            <div>3</div>
        </li>
        <li>
            <div>4</div>
        </li>
        <li>
            <div>5</div>
        </li>
        <li>
            <div>6</div>
        </li>
        <li>
            <div>7</div>
        </li>
    </ul>
</div>

<div id="buttons">
    <button id="left">left</button>
    <button id="right">right</button>
</div>

http://jsfiddle.net/lemonkazi/kj87Lb3b/

Answer №1

There's really no need to start from scratch when there are already plenty of plugins that can achieve what you're looking for. Some of them are lightweight and others are quite powerful.

If I were to suggest one, I'd recommend checking out Owl Carousel 2. It has features like loop support, dynamic widths, touch events, and more.

However, if you still insist on creating your own solution, be mindful of not using fixed values for the wrapper's position calculations:

$(runner).animate({ "left": "-=" + <li real outer width> + "px" }, "slow");

Remember, the actual width of an element may include border sizes as well, so always inspect the outer width during execution.

For handling looping behavior, consider implementing a check based on the wrapper's current position relative to its width. Something along the lines of:

$('#right').click(function() {
    var width = $(~last visible <li>~).outerWidth(); // ~*~ is pseudo-code
    var $runner = $(runner);
    var left = $runner.prop('left') + width < $runner.width()
                 ? "-=" + width + "px"
                 : "0px";

    $runner.animate({ "left": left }, "slow" );
});

And don't forget about handling the positioning of item numbers when transitioning between the last and first items in the carousel.

Simply put:

[5,6,7] -> [6,7,-] -> [7,-,-] -> [0,1,2]

Overall, my advice would be to save yourself the trouble and opt for a reliable carousel plugin instead! ;)

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

Last month's display is currently unidentified

function calculateTime() { var Make_It_12_Hour = true; var currentTime = new Date(); var hour1 = currentTime.getHours() - 1; var hour2 = currentTime.getHours(); var hour3 = currentTime.getHours() + 1; var minutes = currentTime.getM ...

React: Remember to always retain the initial four characters when making changes

I have implemented an input component for phone numbers using the react native phone input library, which automatically adds the international code. However, I am facing an issue where the international code +234 is deleted when the user presses the back b ...

When I hover over div 1, I am attempting to conceal it and reveal div 2 in its place

I need help with a CSS issue involving hiding one div on mouse hover and showing another instead. I attempted to achieve this using pure CSS, but both divs end up hidden. Would jQuery be necessary for this task? Below is the CSS/HTML code I wrote: .r ...

Uploading files with Angular and NodeJS

I am attempting to achieve the following: When a client submits a form, they include their CV AngularJS sends all the form data (including CV) to the Node server Node then saves the CV on the server However, I am encountering difficulties with this proc ...

Using a numeral within a Font Awesome icon symbol to customize a label for a Google Maps marker

I have a Google Maps marker displayed below, applying a Font Awesome icon as the label/icon. However, I am unsure how to a.) change the color of the marker and b.) include a number inside the marker. Referencing this Stack Overflow post This is the code ...

Resizing anchor element using CSS

Hey there, I'm having trouble scaling my anchor tag when hovering over it. Here's the code I'm using: a { color: red; text-decoration: none; transition: all 0.5s; } a:hover { ...

issue with retrieving data from PHP script via ajax

My attempts to use AJAX to call a PHP script have been unsuccessful. I added an echo alert statement in my deleteitem.php script to ensure it was being called, but no matter what I tried, it never executed. Both the PHP script and the JS script calling it ...

When the button is clicked, the JavaScript function is not being executed

I'm having a strange issue with my second button not working as expected. Despite appearing to be straightforward, the "Reset" button does not seem to be triggering the clear() function. Within the HTML code, I have two buttons set up to interact wit ...

How can the Singleton pattern be properly implemented in Typescript/ES6?

class Foo{ } var instance: Foo; export function getFooInstance(){ /* logic */ } or export class Foo{ private static _instance; private constructor(){}; public getInstance(){/* logic */} } // Use it like this Foo.getInstance() I would ...

Transition smoothly between sections using fullPage.js with clipping path effects

I am looking to create a unique clipping animation utilizing SVG clipping path. The animation should hide the first section while revealing the second section in a smooth transition using fullPage.js. This idea is somewhat similar to the question discusse ...

What is the best way to include multiple search parameters in a Node.js URL?

I'm currently working on a project involving react, node, express, and postgress. My main challenge right now is figuring out how to use express routes to pass multiple parameters. For example: Here's the route I am trying to work with: //Get en ...

Challenges with HTML and Session Handling

It's not functioning properly! <?php session_start(); ?> <p class="username"><?php echo $_SESSION['name']; ?></p> ...

Scroll function not functioning properly in Internet Explorer

When attempting to use scroll(x,y) in Internet Explorer 10 with JavaScript, I encountered an issue when trying to run the script on a website. Is there an alternative method that works for IE? This is part of a Java Selenium test where I need to scroll wit ...

What are the steps for scheduling asynchronous tasks using Promises in Node.js?

As a beginner in Javascript, I am struggling to understand how to execute my functions sequentially. My goal is to use Promises to accomplish this task. I am currently following a tutorial on creating a chat bot for Facebook Messenger. Essentially, I want ...

Ways to terminate all AJAX requests within a for loop

Is there a way to cancel all AJAX requests that are being handled by a for loop? var url = ["www.example.com","www.example2.com",....]; for (var i = 0; i < url.length; i++) { var XHR = $.get(url[i], function(data) { //do something }); } I attemp ...

The Next.js Image component does not implement the maxWidth attribute

<Image src="/assets/blog/image.webp" style={{ maxWidth: "700px" }} width={1400} height={1400} /> Issue Detected The image with src '/assets/blog/image.webp' has the following styles applied, but they are being overwrit ...

Querying subdocuments within an array using MongoDB's aggregation framework

Currently, I'm facing a challenge while developing a statistics dashboard for a meditation app. I'm struggling with creating a MongoDB query to fetch the most popular meditations based on user progress. The key collections involved are users and ...

Is it possible to use multiple stylesheets with PhoneGap?

Currently, I am storing a stylesheet (CSS file) from the web server into device storage using the file system access method provided in the phonegap guide for File. I need to apply this stylesheet to my app from the device storage, and will be updating the ...

How can I position text in the top right corner of a v-card's v-img component in Vuetify.js?

I am using Vuetify.js and I am trying to show a single word on the right side of an image within a v-card: <v-card> <v-img src="https://cdn.vuetifyjs.com/images/cards/desert.jpg" aspect-ratio="2.75"> <span class= ...

Navigating with nodeJS

Currently, I am in the process of learning how to create a Node.js project. My latest endeavor involved following a tutorial to develop a chat application. However, it seems like there is an issue with the routing between the server side and client side. ...