Having trouble with jQuery's .animate() on a basic horizontal slider?

I attempted to customize this jQuery slider solution from Stack Overflow: (using the first solution - http://jsfiddle.net/sg3s/rs2QK/).

Check out my modified version on jsFiddle here: http://jsfiddle.net/markrummel/KSHSX/.

The slide-in effect for the DIV element works smoothly, but the one being slid out abruptly disappears instead of sliding out at the same pace. I have made adjustments by removing .hide() in the JavaScript and overflow:hidden in the CSS to observe the movement of the sliding-out DIV.

This is my first experience using the .animate() function, so any guidance you can provide would be highly appreciated!

Below is the JavaScript code snippet:

$('.date-nav-prev').click(function () {
    $('.date-nav-next').show();
    var current = $('.visible-actions');
    var prev = current.prev('.user-actions');
    current.removeClass('visible-actions').animate({
        left: current.width()
    }, 500, function() {
        //current.hide();
    });
    prev.addClass('visible-actions').show().css({
        left: -(prev.width())
    }).animate({
        left: 0
    }, 500);
});

$('.date-nav-next').click(function () {
    var current = $('.visible-actions');
    var next = current.next('.user-actions');
    current.removeClass('visible-actions').animate({
        left: -(current.width())
    }, 500, function() {
        //current.hide();
    });
    next.addClass('visible-actions').show().css({
        left: prev.width()
    }).animate({
        left: 0
    }, 500);
});

Here is the HTML content:

<button class="date-nav-prev">< Prev</button>
<button class="date-nav-next">Next ></button><br />
<div id="wrapper">
  <div class="user-actions daysAgo2">
      Actions from 2 Days Ago</div>
  <div class="user-actions yesterday">
      Yesterday's Actions</div>
  <div class="user-actions today visible-actions">
      Today's Actions</div>
</div>

CSS styling:

.user-actions.yesterday, .user-actions.daysAgo2, .date-nav-next {display:none;}
#wrapper{width:250px; height:300px; border:1px solid #333;position:relative; float:left;
 /*overflow:hidden;*/
}
.user-actions {width:100%; height:100%; position:relative; float:left; overflow:hidden; margin:0;}
.today {background:green;}
.yesterday {background:yellow;}
.daysAgo2 {background:orange;}

Answer №1

I've simplified the entire concept a bit to give you an idea of where it could lead. Most plugins have a wrapper box that slides left and right, not the actual boxes themselves. This simplifies things a bit.

Check out the DEMO.

I introduced a #slider div which moves horizontally:

<button class="date-nav-prev">< Prev</button>
<button class="date-nav-next">Next ></button>
<div id="wrapper">
    <div id="slider">
        <div id="daysAgo2">Actions from 2 Days Ago</div>
        <div id="yesterday">Yesterday's Actions</div>
        <div id="today">Today's Actions</div>
    </div>
</div>

Make sure to set the wrapper to overflow:hidden; so anything outside the current slide is hidden:

#wrapper{
    width:300px; 
    height:300px; 
    border:1px solid #333;
    position:relative; 
    overflow:hidden;
}
#slider {
    width: 1000px;
    height: 100%;
    position: absolute;
}
#slider div {
    width:300px; 
    height:100%; 
    float:left; 
}
#today{background:green;}
#yesterday {background:yellow;}
#daysAgo2 {background:orange;}

You can simply slide the content left and right with the slider. And the beauty of it? You can always expand such sliders without any limitations!

var sliderWidth = 300;
var slider = $('#slider');
var sliderCount = $('div', slider).length;
slider.width(sliderCount * sliderWidth);

$('.date-nav-prev').click(function () { 
    $('#slider').animate({left: '+='+sliderWidth}, 500);
});

$('.date-nav-next').click(function () {
    $('#slider').animate({left: '-='+sliderWidth}, 500);
});

Answer №2

If you're looking to add some dynamic effects to your website, consider using this handy plugin.

$('#wrapper').cycle({
    fx:     'scrollHorz',
    prev:   '#prev',
    next:   '#next',
    timeout: 0
});

Check out an example 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

Adding additional elements to a div in a horizontal orientation

I am currently working on a project where I need to display bars and restaurants based on specific filter criteria. I have a container div called .resultsContainer where all the results will be displayed. While I can easily append more divs (.barContainer) ...

Tips for managing and showcasing various user inputs in an array using JavaScript

I have been tasked with storing multiple user input values in a JavaScript array using the push method. Below is the code: <body> <h3>employee form</h3> <div class="row"> <div class="col-md-6" ...

Tips for altering the color of spans that share a common top position without affecting the surrounding sibling elements above or below

Is there a way to change the color of spans with the same top position, excluding sibling elements above or below, in a paragraph made up of spans? I've been working on how to change the color of the line of span tags that contain another span with t ...

The height of the image will be fetched only once from a large collection of images

As mentioned in the title, I have multiple elements with the same class and I am trying to fetch that class to check for the width/height/src of the child image. I am only able to retrieve the height and width of the first image, but I can get the src of ...

Using the "this" keyword in JavaScript to access the "rel"

Take a look at the JSFIDDLE , where you will notice that the rel attribute in the alert is shown as 'undefined' : var ItemTypeArray = $('input[name^=ItemType]:checked').map(function(){ alert(this.id + ' , r= ' + this.rel) ...

Button Hover Effect: Transition with Style

I am trying to implement a one-second transition from the default color scheme to the hover color for a Button element in Material UI. I am using the transitions.create(props, options) method as described in this article: https://medium.com/@octaviocoria/c ...

What is the best way to smoothly move a fixed-size div from one container to another during a re-render process?

Introduction Anticipated change Similar, though not identical to my scenario: Situation 0: Imagine you have a container (chessboard with divs for game pieces) and a dead-pieces-view (container for defeated pieces). The positioning of these containers i ...

What is the best way to share the recipient's address with the browser link?

I am currently working on a project using PHP Zend with SQL Server 2008, jQuery, and AJAX. My goal is to send an email containing a webpage link to a specific client and receive feedback from them. I want to ensure that only the intended recipient is abl ...

Are the jQuery selectors provided by the client safe to use?

Is it secure to let users input jQuery selectors for selection? I am considering taking a selector string submitted by users, which could potentially be malicious, and using it in $('') to target elements on the webpage. ...

What is the purpose of utilizing jQuery for retrieving CSS resources?

Upon reviewing the Chrome Dev Tools screenshot, I am puzzled by the fact that my CSS assets are being fetched by jQuery. The CSS sheet is included in the normal way, using a <link rel="stylesheet"> tag in the <head> section, while jQu ...

What is the reason behind the vanishing of the input field while adjusting the

Why is the input field getting cut off when I resize my browser window, even though I'm using percentages? Here is a screenshot for reference: https://i.sstatic.net/4JrWd.png Shouldn't it resize automatically with percentages? Thank you! Below i ...

Unable to locate the div element during the Ajax request

I have implemented an AJAX call on a div with the class 'mydiv' as shown below: However, I am encountering difficulty in locating the parent div within the success section. <div class="mydiv"> <a href="/jewelry/asscher-cut-diamond- ...

Send an array from PHP to jQuery using AJAX, then send the array back from jQuery to PHP

I am facing a dilemma where I am passing an array from PHP to jQuery AJAX using `json_encode` and storing it in an empty array declared in the jQuery script as `var myarr = []`. Later in the same script, I am sending the same array `myarr` back to the PHP ...

Should Angular Flex Layout be considered a top choice for upcoming development projects?

Should I consider using Angular Flex Layout for upcoming projects, even though it is considered deprecated? Despite its deprecation, there are still a high number of weekly downloads on npmjs.com. I am in the process of starting a new Angular project usin ...

Issue with Jquery Fly To Cart Animation on Mobile Devices

On desktop view, I successfully added a 'fly to cart on click' function, but when switching to mobile view, it flies to the left side of the screen where my cart icon is not located. It essentially flies to the 'hamburger menu.' I' ...

Encountering difficulties while attempting to convert JSON to XML resulting in an error being

I can't seem to figure out how to successfully convert the JSON result into XML format. I've tried the code below but it's not working as expected. Any help would be greatly appreciated. Here is the code snippet: <script src="../Jquery ...

how can I transfer model values to a dashboard in Rails 5?

I have developed an app that includes an adminlte dashboard. The dashboard is populated with various values obtained by a jQuery file. I am trying to pass module values to the dashboard. For example, the number of users shown in the dashboard should be fet ...

Attaching the CSS file to the Haml layout template

I'm currently working on linking a css file to a haml layout template Within the ApplicationHelper class, I have a method to properly generate html module ApplicationHelper def styletag(sheet_name) "<link rel='stylesheet' href=&a ...

Utilize HTML to resize image to fit within container

I've encountered an issue while working with Adobe Dreamweaver CS5. I added a swap behavior to an image in an html document, expecting it to pop up at its original size and restore on mouse out. However, the swapped image ends up filling the entire sc ...

"Utilizing the power of Twitter Bootstrap and Snap.js for

I am currently working on integrating Snap.js by jakiestfu with Twitter Bootstrap. I have managed to make it work to some extent (I can slide the content and open a drawer through a click event). However, I am facing a challenge where the drawer content re ...