Here is a unique version: "A guide on centering a carousel item in jquery upon being clicked."

Does anyone know how to center the item I click in a carousel? I've searched high and low for a solution but couldn't find a clear answer. Can someone please assist me with this?

This is what I have tried so far: http://jsfiddle.net/sp9Jv/

Here is the HTML code snippet:

<div id="wrapper">
    <div id="carousel">
        <a href="#" class="prev">prev</a>
        <a href="#" class="next">next</a>

        <div class="viewport">
            <ul>
                <li><a href="#">Un</a></li>
                <li><a href="#">Deux</a></li>
                <li><a href="#">Trois</a></li>
                <li><a href="#">Quatre</a></li>
                <li><a href="#">Cinq</a></li>
                <li><a href="#">Six</a></li>
                <li><a href="#">Sept</a></li>
                <li><a href="#">Huit</a></li>
            </ul>
        </div>
        <!-- viewport -->

    </div>
    <!-- carousel -->
</div>
<!-- wrapper -->

The JavaScript part:

var carousel = $('#carousel'),
    prev = carousel.find('.prev'),
    next = carousel.find('.next'),
    viewport = carousel.find('.viewport'),
    item = viewport.find('li'),
    itemWidth = item.outerWidth(true),
    itemNum = item.length,
    itemList = viewport.find('ul');

itemList.width(itemWidth * itemNum);

var moveCarousel = function(dir) {
    itemList.animate({ left: '-=' + (itemWidth  * dir) + 'px' }, 400);  
};

//prev
prev.on('click', function(e) {
    e.preventDefault();
    moveCarousel(-1);
});

//next
next.on('click', function(e) {
    e.preventDefault();
    moveCarousel(1);
});

//when carousel items are clicked
item.on('click', 'a', function(e) {
    var self = $(this),
        selfIndex = self.index(),
        distance = itemList.width() / 2,
        selfPos = self.position(),
        selfPosLeft = selfPos.left,
        viewportPosLeft = viewport.position().left;

    e.preventDefault();

    //center the clicked item, not working properly yet 
    if (selfPosLeft > Math.floor(viewport.width())/3) {
        itemList.animate({ left: '-' + Math.floor(viewport.width())/3 + 'px' }, 400);
    }

    if (selfPosLeft < Math.floor(viewport.width())/3) {
        itemList.animate({ left: Math.floor(viewport.width())/3 + 'px' }, 400);
    }
});

The CSS styles:

#wrapper {
    width: 500px;
    margin: 20px auto;
}
#carousel {
    position: relative;
}
.viewport {
    width: 260px;
    border: 1px solid #6e6e6e;
    height: 80px;
    overflow: hidden;
    position: relative;
    margin-left: 100px;
}
.prev, .next {
    position: absolute;
}
.prev {
    top: 20px;
    left: 0;
}
.next {
    top: 20px;
    right: 0;
}

.viewport ul {
    position: absolute;
}
.viewport li {
    float: left;
    margin-right: 10px;
}
.viewport li a {
    display: block;
    width: 80px;
    height: 80px;
    background: #ddd;
}

Answer №1

After gathering all the necessary information about every item, it's possible to determine the value of the left position based on which item is clicked.

Here is a revised version:

I have linked the click functionality of carousel items with a specific function and passed the clicked item using the self keyword.

var itemClicked=function(item){
    var itemIndex=$(item).index(),
        newLeft=(itemIndex*itemWidth*-1)+Math.floor(($(viewport).width()/itemWidth)/2)*itemWidth;
    $(itemList).animate({left:newLeft+"px"},400);
};

You can see this in action at the following URL: http://jsfiddle.net/rUZHg/3/

This method should work regardless of how many elements are being viewed, as it calculates the padding between the left 0 and the center element's left position.

Answer №2

Okay, it may not be the most visually appealing design, but hopefully it sparks some inspiration for you.

I implemented a global variable called currentItem to keep track of the item in the center of the carousel. This variable gets updated every time the carousel moves.

One key variable that proved to be useful was selfPosLeft, which helped me identify the clicked item. Interestingly, I discovered that the value 90 seemed to play a significant role, possibly related to CSS styling. It's worth investigating how this number is determined dynamically.

Give it a try and see how it works for you :) http://jsfiddle.net/sp9Jv/4/

As you expand beyond 3 items, consider modifying the code to calculate the difference between the current item and the selfPosLeft of the selected item. I'll leave that customization up to you :) The current setup appears to function well. http://jsfiddle.net/sp9Jv/5/

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

Show various Bootstrap Alert Messages based on the type of error detected?

Trying to figure out how best to explain this, here it goes! I am working on a website and I want to incorporate alert messages. Check out some examples here. Depending on the form inputs, I need different alerts to be displayed. PHP will validate the in ...

Finding the previous and next dates can be easily accomplished by combining the power of jQuery, AJAX

I have created a calendar using PHP with previous and next buttons. I am now looking to implement AJAX functionality to navigate to the previous or next date without reloading the page. Within the PHP file called by AJAX, I have a query that retrieves tas ...

Aligning two images vertically using the display: table-cell property

I'm trying to align two images vertically using CSS' display: table-cell property, but it doesn't seem to be working even after specifying the height. <div style='display: table;height:500px'> <div style=' displa ...

The `val()` method in jQuery does not retrieve the value from every input field

Here is the HTML code I am working with: <input type="text" id="fname" name="fname" placeholder="First Name" /> <input type="text" id="lname" name="lname" placeholder="Last Name" /> <input type="text" id="birthdate" name="birthdate" placeho ...

Input form and select form collide in conflict when the "Enter" key is activated

My search box includes input forms and a select form with various options. The issue arises when using the place autocomplete feature from Google Maps alongside the select form. When the enter key is pressed after entering a location in the autocomplete fi ...

Retrieve the node-postgres result and store it in a separate object beyond the callback function

Currently, I am in the process of converting a data profiling script originally written in Python to JavaScript while following the Wes Bos beginner Javascript Course. This script is designed to take database connection details and a specified target tabl ...

Utilizing HTML, CSS, and JavaScript to dynamically add and remove a class from

I've been struggling with a specific issue in my 9-button grid. When I click on a button and it changes color to orange, if I click on another button, both buttons remain orange. What I want is for only one button at a time to be orange - when a new b ...

Framework7 initialization not triggering when page is initialized

Unable to get init function working in my Framework 7 app. I have attempted all the solutions provided in the following link: Framework7 Page Init Event Not Firing // Setting up Application var myApp = new Framework7({ animateNavBackIcon: true, ...

Discovering every row in a table's <tbody> section through the power of jQuery

I am struggling to fetch all rows from a <tbody> segment in a table, and I need guidance on the correct syntax. Below is a sample snippet of the table structure along with my latest attempt using jQuery! Table segment: <tbody> <tr> & ...

Resize a responsive grid of images

Within my slider, I have three slides with 3 images each. The layout consists of one large image on the left and two smaller ones on the right. To ensure responsiveness, I've used max-width: 100% on the images so they can scale down proportionally as ...

Tips for implementing a method to switch CSS properties of a main container by using a checkbox within its child element in a Svelte component

It took me a while to figure this out, but I still feel like my implementation is not ideal. I'm confused as to why things break when I remove the checkedActivities.has(activity) ? "checked" : "unchecked", because I thought TypeScr ...

Issue with code failing to insert object into an array

I've been struggling to add a group of objects from a JSON file into an array. Despite trying to use the push method, the length of the array remains at 0. I'm puzzled by what could be going wrong. The JSON data is being parsed correctly as I&apo ...

How can I convert the stylesheet link from fonts.google.com into a CSS class and include it in my file.css as an internal style instead of an external one?

Looking to incorporate a font from fonts.google.com? Here's how you can do it: <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css2?family=Source+Sans+Pro:wght@200;300 ...

What could be causing this conflicting behavior with the logical "and" operator?

const {DEMO, PORT, LOCAL} = process.env; const socketAddress = (DEMO & LOCAL)? `http://${hostname}:${PORT}`: `wss://${hostname}`; When DEMO is false, PORT is undefined, and LOCAL is true The hostname being used is http://9f9cbf19.ngrok.io I verified ...

Replace the hyphen with a comma using JavaScript

Looking for a way to modify a string like this: "PALS español K- add-on" by replacing the - with ,. The desired output should be: "PALS español K, add-on" Is there a JavaScript solution to achieve this task? ...

Ten instances of $digest() being triggered upon the implementation of custom filters

I am struggling with the following angular markup: <tr ng-repeat="dia in dias"> <td>{{ dia[0].fecha }}</td> <td ng-repeat="bloque in bloques"> <div ng-repeat="hora in dia|soloBloque:bloque|sacarHoras"> ...

How can a JQuery function be used with SVG to trigger a second animation immediately after the first animation is finished?

For the handwriting effect animation, I utilized the animation-delay technique by dividing the object wherever it intersected, drawing paths, and converting them into clipping masks. This involved breaking the letter "W" into four parts, creating different ...

elevate design css/widget/components

I am currently on the lookout for samples of boot strap floating css/widget/parts. Despite googling with keywords like 'floating / fixed', I have only come across sticky footer and header examples, or some simple panel samples. By 'floatin ...

Customizing icons in jQuery alongside text: Tips and tricks

Here is the JsFiddle I'm currently working with: <div class="col-md-6"> <a id="IdAdvanceSearch" href="javascript:;" class="col-sm-offset-2" data-advance-search="S"> Show Advance Search <span class="glyphicon glyphi ...

Switch out the view div element with ui-router

Currently, I am utilizing Angular ui-router to manage various views in the following manner: <div ui-view="header"></div> <div ui-view="nav"></div> <div ui-view></div> Upon Angular loading, the divs are automatically p ...