Scrolling down to a specific list item and pausing when the li element is in the middle of the

Hello everyone, I'm currently working on creating a carousel. I have used list items with images inside and am using scroll to navigate to a specific list item. However, when clicking on a thumbnail (let's say the 2nd one), it scrolls to the image inside the LI and sets the image margin-left to 0px. What I really want is for the scroll to center the image instead.

Try clicking on the 4th thumb to view the desired effect.

I have created a fiddle for reference: MyFiddle

jQuery(document).ready(function($) {
        $("#fourthThumb").click(function() {

            $('html, body').animate({
                scrollLeft: $("#fourthImage").offset().left
            }, 2000);
        });
    });

Any suggestions on how to stop the scroll once the 4th image is centered would be greatly appreciated. Thank you.

Answer №1

To ensure versatility across all images, it is recommended to implement a dynamic solution. Check out this DEMO for live testing.

$(document).ready(function() {
    $("#thumbsList li").click(function() {                
        var windowWidth = $(window).width()/2;
        var index = $(this).index();
        var currentImage = $("#imagesList li img:eq("+index+")");
        var imageWidth = currentImage.width()/2;
        $('html, body').animate({                    
          scrollLeft: ((currentImage.offset().left)-windowWidth+imageWidth)
        }, 1000);
    });
});

Answer №2

Do you think this solution would be effective for your specific situation?

    jQuery(document).ready(function($) {
        $("#fourthThumb").click(function() {                
            var windowWidth = jQuery(window).width()/2;
            var imagewidth = $("#fourthImage").width()/2;
            $('html, body').animate({                    
                scrollLeft: (($("#fourthImage").offset().left)-windowWidth+imagewidth)
            }, 2000);
        });
    });

Check out the implementation here

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

Tips for preventing CSS animation from reverting back to its initial position

After transforming 2 div tags into blocks, I created a code that causes the blocks to move outwards. The issue I'm facing is that they return to their original position after moving. I want the two blocks in the animation to move out to the sides and ...

Loop through the JavaScript array and continuously display the last item in the array. Repeat this process indefinitely

I am working on a code to create a "fade-In fade-Out" effect for text. However, I'm facing an issue where the text displayed is always the last value in the array instead of changing to the next one each time it fades in and out. Here is the HTML cod ...

Issue with Flex property not being supported in Safari browser

.rq-search-container { position: relative; width: 100%; background: white; display: flex; flex-direction: row; align-items: flex-start; border-radius: 2px; z-index: 30; -webkit-flex: 1 0 15em; } While this code functi ...

Tips for showcasing chats with the most recent message highlighted

As I work on my web app using Laravel, I have encountered an issue where I need to scroll down to see the newest messages when there are many conversations. Here is how the chats display on page load I want to focus on displaying the newest message first. ...

What is the best way to incorporate data retrieved from a GET request into a CSS method?

Within my jQuery script, I am utilizing the get function to retrieve data from an external PHP page named "external.php". The extracted data is a basic path leading to an image (such as images/house.jpg). My goal is to utilize this path to set the backgrou ...

Update Mapbox popups following filtering

I have successfully constructed a Mapbox map with a complex custom popup structure, complete with photos and formatting. The data is being fed from a .csv file using omnivore, and the popups are being created on ready. Additionally, I have implemented a se ...

Guide to automatically triggering overscrolling

Currently working on a kiosk webpage designed for an iPad. Discovered an app that enables fullscreen mode, but requires overscrolling at the bottom. Is there a method to automatically trigger this on my webpage? Attempted to achieve this using autoscroll ...

Encountering the issue of 'Uncaught SyntaxError: Unexpected token <'

I keep encountering this error repeatedly. I followed the example at https://facebook.github.io/react/docs/thinking-in-react.html#step-5-add-inverse-data-flow and it works perfectly on jsfiddle. However, when I try to implement the same code in mvc's ...

What is the best way to flip the direction of the text input for a Calculator?

I am currently working on creating a basic calculator from scratch using HTML, CSS, and JavaScript. I have been trying to figure out how to align the numbers to the right side of the input element. Can anyone provide me with guidance on how to achieve thi ...

The second div element remains unselected in jQuery

Below is the example of an HTML structure: <span id="17">yes here</span> <div class="PricevariantModification vm-nodisplay"></div> <div class="PricesalesPrice vm-display vm-price-value"> <span class="a"></span> ...

Using C# to trigger a jQuery function by clicking a button

My current issue involves loading a cropped image into the asp:image without relying on Updatepanel. The problem is that while the image displays, it requires the $('.image-cropper').each(linkUp); function within jQuery(window).load() to begin th ...

Extracting multiple values using the .find method in JQUERY / JavaScript

I'm facing an issue with my JSP page form. When I submit the form, it generates a JSON string which is sent via AJAX post. The problem arises when I try to extract multiple values from the form using the following method: .find('input[name=ite ...

A placeholder within the HTML <code> element

Is there a way to include a placeholder attribute in the < code> < /code> tag similar to the < input> < /input> tag? <input type="text" name="fname" placeholder="First name"><br> ...

Advancing background gradients with CSS

Looking for help with CSS to create specific effects? I have the gradient covered, but struggling with rounded corners in some areas. Any suggestions? Check out this blue background and also this blue background Appreciate any advice you can provide. Tha ...

Using JavaScript to set the value of an input text field in HTML is not functioning as expected

I am a beginner in the programming world and I am facing a minor issue My challenge lies with a form called "fr" that has an input text box labeled "in" and a variable "n" holding the value of "my text". Below is the code snippet: <html> <head&g ...

Employing AJAX to send form data to a pair of destinations

Can anyone help me out? I am having trouble using AJAX to submit my form to one location and then to another. Once it's posted to the second location, I want it to send an email with PHP to a specified recipient, but for some reason, it's not wor ...

How do I make an element stay in place between two other elements?

Trying to make an element "float" between two other elements using the `position : sticky` attribute. Not achieving the desired effect and unable to determine why. The goal is for the `copy` to float between the bottom of `upper` and the top of `lower`. ...

When the document is shifted by an angular function call, the mouseup event fails to trigger

My problem involves an angular function that alters the ng-if state to display the sidebar when the image is clicked. However, upon calling the function and shifting the entire webpage, the mouseup event for the image no longer triggers when I release th ...

What is the best way to completely stretch 2 embedded div elements?

Is there a way to stretch two <div> elements to be 50% wide? Here is a jsFiddle with the solution. HTML <div class="container"> <div class="left">left</div> <div class="right">right</div> </div> CSS di ...

Saving models using Django and Ajax

My goal is to use ajax to post data, saving a model successfully and returning the response as a JSON object. Below is the jQuery-based ajax post I am using: var requestData = { 'ievent_id': type , 'channel_id': CHANNEL_ID , 'sta ...