The slider is experiencing trouble with its display

I am trying to create a simple slider using the margin-left css property. However, it seems that the result is not displaying correctly with partial margin-left increments. Can anyone help me figure out what is wrong with my code?

Check out the code on jsFiddle here.

Here is the HTML:

<div class="main-padding">
    <div id="wrapper-slider">
        <div class="item-slider item-slider1"></div>
        <div class="item-slider item-slider2"></div>
        <div class="item-slider item-slider3"></div>
    </div>
</div>

This is the CSS being used:

* {
    border: 0;
    margin: 0;
    padding: 0;
    outline: 0;
}

a {
    text-decoration: none;
    color: inherit;
}

body {
    font-size: 62.5%;
}

ul, ol {
    list-style-type: none;
}

.main-padding {
    padding: 20px;
}


#wrapper-slider {
    height: 200px;
    position: relative;
    overflow: hidden;
}

.item-slider {
    width: 100%;
    float: left;
    height: 100%;
}

.item-slider1 {
    background-color: red;
}

.item-slider2 {
    background-color: blue;
}

.item-slider3 {
    background-color: yellow;
}

And here is the jQuery function being applied:

$(function () {

    var item = ".item-slider";
    var next = 1;
    setInterval(function() {
        $(item + next).animate({"marginLeft": "-100%"}, 1000);
        next++;
    }, 2000);

});

Answer №1

The primary issue with your slider lies in how you've defined the elements of the slider to float. I've implemented some modifications to your code to ensure it functions as intended.

CSS Changes:

.item-slider {
    position: absolute;
    left: 100%;
    width: 100%;
    height: 100%;
}

JavaScript Updates:

$(function () {

    var item = ".item-slider";
    var next = 1;
    var current;
    setInterval(function() {
        if(next === 1){
            prev = $(item + 3);
        }else{
            prev = $(item + (next - 1));
        }
        current = $(item + next);
        current.css({"left": "100%"});
        current.animate({"left": "0"}, 1000);
        prev.animate({"left": "-100%"}, 1000);
        if(next === 3){
            next = 1;
        }else{
            next++;
        }
    }, 2000);

});

See Updated Fiddle Here: https://jsfiddle.net/lmgonzalves/1utkr6et/5/

Answer №2

To ensure proper display of the slider, it is important to define a width for the wrapper-slider, such as width:300%; (100% for each slide). However, using padding for main-padding can cause issues with the slides appearing too close together, resulting in about 20px of the next slide being visible. It may be advisable to avoid using padding, as demonstrated in the Demo.

Additionally, calculating the width of each slide is necessary.

Check out the Demo:

https://jsfiddle.net/twgvxj1z/

Implementation in Code:

var windowWidth = $(window).width();
$(".item-slider").css("width", windowWidth+"px");

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

The term "Ext" has not been recognized or defined

Currently, I am facing an issue while attempting to integrate a TinyMCE plugin with ExtJs. I found a helpful demo example at this link, which I followed closely. However, my implementation is failing as I am receiving an error message stating "Ext is not ...

What is the best way to delete these <li> tags according to their respective timestamps?

When the page loads, there are initially 5 <li> elements. Additional <li> elements are then randomly added every few seconds. I want to remove any <li> elements that have been on the page for more than a minute. My plan is to create an ...

Struggling to align HTML with inspect page using selenium in Python 3

Embarking on my programming journey, I've decided to create a web scraping program for the fun of it. My girlfriend and I are hooked on Animal Crossing and have been engrossed in the turnip game. There's a webpage where players post their turnip ...

Is it possible to identify the origin URL of a user using Javascript or AngularJS?

Is it possible to use Angular to detect the origin URL of a user visiting my website in order to perform specific operations later on? ...

Generate random images and text using a script that pulls content from an array

My goal is to have my website refresh with a random piece of text and image from an array when a button is clicked. I have successfully implemented the text generation part, but I am unsure how to incorporate images. Here is the current script for the text ...

Configuring IP Whitelisting for Firebase Cloud Functions with MongoDB Cluster

What is the process for including my Firebase Cloud Functions in the IP whitelist of my MongoDB cluster? Error Message: ...

Ensuring validation for a single checked checkbox in AngularJS

I'm currently experiencing a challenge with checkboxes in my Angular project. Due to the requirements of the backend, each checkbox must have a unique name, but at least one of them needs to be checked before the form can be submitted. To address thi ...

Unable to convert UTF-8 buffer to the specified data format

Before flagging this question as a duplicate, I want to clarify that I have already tried various solutions found in different threads to convert a buffer into an array of buffers, but none of them meet my requirements. I am currently using Node's ch ...

Tips for making a rounded bottom image slider with react-native?

Is there a way to design an image slider similar to this with rounded bottom images? ...

Guide on ensuring a THREE JS model maintains constant orientation towards cursor pointer

I'm working on a 3D model that currently follows the mouse only when clicked. However, I am looking to make it move without requiring the click so that it always faces the cursor pointer. The project is built using THREE.JS. Is there a way to achieve ...

What is the process for triggering a PHP function when a form element is clicked in a webpage?

Currently, I am trying to implement a jQuery colorbox on my webpage which appears over a <select> drop-down list. My goal is to trigger an AJAX call every time a new option is selected from the drop-down. Even though I have written the following cod ...

Adjust the width of the react-bootstrap container

Is there a way to make the default container width in Bootstrap smaller while ensuring it remains consistent across all viewports? I am looking to decrease the total width of the container, making it relatively shorter than its current size. How can I ach ...

Issue with long text in a resizable table using jQuery tablesorter 2.31.1

My issue is that when I try to resize the columns in tablesorter, they snap back into place. The column width set with resizable_widths does not apply correctly until a column is manually resized. Despite setting the width of all cells to 120px, any cells ...

Determine the previous day's date using JavaScript by subtracting one day

I am facing an issue while attempting to store a specific date format in MongoDB. Instead of saving the date as intended, it is consistently registering a day earlier than specified. For instance - db.test.insert({name: "test1", dob: new Date(1986, 11, ...

Retrieving information from Laravel route using React

In my Laravel application utilizing Laravel Framework 8.83.16, I have implemented the following function: public function checkIdentifier($physicalItem_identifier) { try { $con = "mysql"; $res = DB::connec ...

What steps can be taken to ensure that the on-click feature does not require continuous mouse holding to remain active?

I'm working on getting my search boxes to change color when clicked, but currently it only changes color while I am holding down the mouse button. Once I release the cursor, it reverts back to its original color. How can I make it so that it changes c ...

Preventing the jQuery UI slider from exceeding a specified limit value

My webpage features multiple sliders, each with varying scales. Some go up to 150 and others up to 200. I want to set a maximum limit of 200 for all sliders, but restrict some from moving past the 150 mark. These sliders are different $().slider() calls, s ...

Call stack limit exceeded, please reduce the recursion depth

I have been working on a project where I need to download encrypted images and decrypt them using RNcryptor in a JavaScript web application, then display them within the HTML of my app. Everything is functioning perfectly except for when the images are lar ...

When running the command "npx create-next-app@latest --ts," be aware that there are 3 high severity vulnerabilities present. One of the vulnerabilities is that "node-fetch

Just set up a fresh project with Next.js and TypeScript by following the documentation using npx create-next-app@latest --ts. Encountering multiple high severity vulnerabilities despite running npm audit fix --force, which actually adds more vulnerabiliti ...

Animating elements with a right-to-left transform in CSS

In my current project, I am implementing a navigation bar that slides a menu from right to left. When the user clicks on their profile picture, the hidden menu is revealed. To achieve this functionality, I utilize the addition of classes hidden and show t ...