Slider displays images generated by PHP in a horizontal motion

Currently, I am in the process of creating a custom horizontal slider for my client's personalized gallery. The gallery comprises elements displayed as a no-wrap, multi-window-width block, designed to change its margin-left when the slider arrows are clicked.

The increment/decrement value for the margin-left needs to be adjustable through a variable, ensuring that it remains functional regardless of the current responsive CSS document loaded.

I attempted to develop a script where the width of the photo-container div is obtained, saved as a variable, and then utilized as the right-hand argument in the animate() function. However, this approach did not yield the desired outcome. In fact, it failed to work entirely, often resulting in an invalid tween error displayed in the console.

Here is my script:

$(document).ready(function() {
           var imageWidthToSlice = $(".gallery-element-wrapper").css("width");
            imageWidth = imageWidthToSlice.slice(0, -2);
            defaultMargin = $(".gallery-element-wrapper:first").css("margin-left").slice(0, -2);
            numberOfElements = $(".gallery-element-wrapper").length;
            totalWidth = imageWidth * numberOfElements;

            $(".gallery-arrow").click(function() {
               if ( $(".gallery-element-wrapper:first").css("margin-left").slice(0, -2) != defaultMargin ) {
                   $(".gallery-element-wrapper:first").animate({
                       marginLeft: "+="imageWidth;
                   },500);
               } 
                else {
                    console.log("This is the first image, can't slide left more.");
                }
            });

        });

Visual overview on the subject: https://i.sstatic.net/THZ6d.jpg

Also available on JSFiddle:

https://jsfiddle.net/akpwb5b9/

Answer №1

Give this a try.

$(document).ready(function() {
        var imageWidthToSlice = $(".gallery-element-wrapper").css("width");
        imageWidth = imageWidthToSlice.slice(0, -2);
        defaultMargin = $(".gallery-element-wrapper:first").css("margin-left").slice(0, -2);
        numberOfElements = $(".gallery-element-wrapper").length;
        totalWidth = imageWidth * numberOfElements;

        $(document).on("click",".gallery-arrow-wrapper",function() {

           if ( $(".gallery-element-wrapper:first").css("margin-left").slice(0, -2) != defaultMargin ) {
               $(".gallery-element-wrapper:first").animate({
                   marginLeft: "+="+imageWidth
               },500);
           } 
            else {
          $(".gallery-element-wrapper:first").animate({
                   marginLeft: "+="+500
               },500);

                console.log("This is the first image, can't slide left more.");
            }
        });

    });

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 running a dry default with Angular CLI

Query: Can dry-run be set as the default in a configuration? Purpose: Enabling dry-run by default simplifies the learning process by minimizing clean-up tasks if the command is not correct. This can encourage users to always perform a test run before exec ...

Attempting to align two text boxes in the center using the text-align property

I've been attempting to center two text boxes using text-align. Unfortunately, they didn't align properly, as evident in this snapshot: https://gyazo.com/c47f4037ba1ab3abef5833358d94172e. What could have caused this misalignment, and how can it b ...

Getting information in the constructor

Is it considered beneficial to retrieve data in the JavaScript class constructor method? For example, in a React class constructor, most tutorials recommend fetching data in the componendDidMount() method. However, there is little explanation as to why we ...

Side menu and grid display using HTML and CSS

Looking to revamp the layout of my angularJS website, specifically one page. Currently, information is displayed in a table format but I would like to switch it up by adding a left sidebar featuring a list of names (tiles). When a user clicks on a name, th ...

What is the best way to animate or manipulate individual points on a 3D plane using three.js?

I have applied a texture to a plane. If I only want to move specific points within the plane, how can I achieve this? For instance, I would like to animate the bottom right corner at a certain speed and the top right corner at a different speed. var came ...

Troubleshooting issue: jQuery UI sortable feature malfunctioning when loading HTML data via

Recently diving into the world of jQuery, I've encountered an issue with my sortable list not functioning properly using the sortable feature. I'm just in the midst of practicing and learning more about it. Here is a snippet of my code: ...

Ways to change the background image when hovering in a React component

I'm having trouble trying to scale my background image by 1.5 when the user's mouse enters. Here is the code I have so far: import React from 'react'; import Slider from './index'; import horizontalCss from './css/hori ...

Issues with character encoding in $.ajax prompts troubleshooting headaches

I am encountering an issue with my PHP page (encoded as 'windows-1251') that includes a $.ajax sender: <div style='float:left;' id='commentRegistration'> <input id='add ...

The 'float' property in HTML and CSS

Good day everyone! I apologize in advance if my explanation is not very clear. Below is my code along with a link to an image that will help illustrate the issue I am facing. Here is the code snippet: <header> <div> <a href="index.html ...

Retrieving the value from an Object within a Mongoose query result

My query looks like this const result = await Form.findOne({ _id: req.params.id }); And here is the output of my query: { _id: 5a8ea110d7371b7e5040d5c9, _user: 5a5c277f8d82ba3644b971c2, formDate: 2018-02-22T10:53:04.579Z, formElement: { form ...

Unusual occurrence in Chrome when checking definitions: ReferenceError: x is not defined

Recently, I've come across some odd behavior in Chrome following its latest update. Whenever I try to determine if a variable is defined, it ends up triggering an uncaught error like the one shown below: if(x) { alert('x is defined.'); } T ...

Adjust the response based on the server's reply when using AJAX

Check out my C# code snippet: if (!String.IsNullOrEmpty(bookRoom)) { ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1); //Update the version as needed in the future //service.UseDefaultCredentials = true; servic ...

Issue with Typescript: When inside a non-arrow class method, the keyword "this" is undefined

Many questions have addressed the topic of "this" in both JS and TS, but I have not been able to find a solution to my specific problem. It seems like I might be missing something fundamental, and it's difficult to search for an answer amidst the sea ...

Is there a way to stream an mp3 file in a Node.js REPL on Replit?

I have an MP3 file that I want to play when a button is clicked. However, I suspect that I am not correctly serving the file to the server. The following code snippet is from my project on Replit.com: const app = require('express')(); const http ...

Create a custom slider using jQuery that pulls in real-time data for a dynamic user

My goal is to implement a dynamic slider feature in my Django project by using jQuery and ajax. I have managed to create previous and next buttons for swiping through profiles with the help of others, but I am currently facing an issue with a NoReverseMatc ...

Troubleshooting ng-repeat in AngularJS: Multi checkbox filter malfunction

My AngularJS app has multiple age range filters implemented, but one of them is not functioning correctly and I can't figure out why. You can view a functional example here. The various filters are defined as follows: .filter('five', func ...

Using Jquery to enhance navigation tabs with pointers

I am facing an issue where the class .hover and .over are added to the entire list whenever I mouseover any list item. I understand that this is happening due to my jQuery code, but I would like to find a way for jQuery to only add the class to the specifi ...

Create a functional component in React.js and Material-UI to display data

I am facing an issue with data management, where multiple titles are being rendered in my table when trying to display data from the Pokemon API. I attempted to move only the data to a separate component but was unsuccessful. Any suggestions on how to res ...

AJAX: The form submission without refreshing the page only functions for the first attempt

My current issue involves using AJAX to submit a form without refreshing the page. The problem arises when I try to submit the form more than once, as the on('submit') function stops working after the initial submission. This defeats the purpose ...

Every time an input is altered, the onClick function is invoked

I am facing an issue while trying to send data to a local server using an onclick function. Every time the input field is changed, the function gets called unnecessarily and I can't seem to figure out why this is happening. const sendDataToServer = () ...