Use jQuery to smoothly scroll a div

I created a container using a <div> element which is divided into 3 inner divs. The first two inner divs are meant to serve as previous and next buttons, with ids of prev and next respectively. At the bottom, there are 3 more inner divs, each with unique ids of diva, divb, and divc. Both divb and divc have their widths set to 0 in order to keep them hidden, while only diva is visible initially. My goal is to hide diva by setting its width to 0, then display divb when the user clicks on the element with id of "next". If the same button is clicked again, I intend for divb to be hidden and for divc to become visible. This process should also be reversible if the element with id of "prev" is clicked.

For a visual representation of my description, refer to the image below:

This link contains a fiddle showcasing this concept.

Answer №1

Using a class, I have implemented the necessary functionality for you. Click on this DEMO to see it in action.

Here is the complete code snippet:

var $pages = $('.page');
$('#nxt').click(
  function() {
    var $cur = $('.active');       //retrieve current active element
    var $next = $cur.next();       //get the next element after the current one

    /*
     * Insert your logic inside the following if statement to go back 
     * to the first div.
    */
    if ($next.length == 0) return; //if there is nothing in the next element, exit the function.

    $cur.removeClass('active');    //remove the active class from the current active element
    $next.addClass('active');      //set the next element as the new active element

    //animate all elements except the one with the 'active' class (which is the next element)
    $('.page').not('.active').animate({"width": 0}, "slow"); 

    //animate the current element (which was set as the next one)
    $('.active').animate({"width": 200}, "slow");
});

$('#prev').click(
  function() {
    var $cur = $('.active');
    var $prev = $cur.prev('.page');

    if ($prev.length == 0) return;

    $cur.removeClass('active');
    $prev.addClass('active');

    $('.page').not('.active').animate({"width": 0}, "slow");
    $('.active').animate({"width": 200}, "slow");
});

Answer №2

View this demo on JSFiddle: http://jsfiddle.net/3yrsu/1/

An additional custom attribute named 'current' has been introduced to monitor the current slide. Furthermore, a class has been included for easy identification of the slides.

Here is the HTML structure:

<div class="scroll">
    <div class="buttons">
        <a id="prev">Previous</a>
        <a id="middle">Test</a>
        <a id="nxt">Next</a>
    </div>
    <div id="diva" class="slide" current="1">div AA</div>
    <div id="divb" class="slide">div BB</div>
    <div id="divc" class="slide">div CC</div>
</div>

The JavaScript implementation is as follows:

$('#nxt').click(
function() {

    var current = $('.slide[current="1"]');
    var next = current.next('.slide');
    var prev = current.prev('.slide');
    if(next.length == 0) {
        next = $('.slide').first().insertAfter(current);
    }
    if(prev.length == 0) {
        prev = $('.slide').last().insertBefore(current);
    }

    current.animate({"width": 0}, "slow");
    next.animate({"width": 200}, "slow");
    prev.animate({"width": 0}, "slow");

    $('.slide').removeAttr('current');
    next.attr('current', "1");

});

$('#prev').click(
function() {

    var current = $('.slide[current="1"]');
    var next = current.prev('.slide');
    var prev = current.next('.slide');

    if(next.length == 0) {
        next = $('.slide').last().insertBefore(current);
    }
    if(prev.length == 0) {
        prev = $('.slide').first().insertAfter(current);
    }

    current.animate({"width": 0}, "slow");
    next.animate({"width": 200}, "slow");
    prev.animate({"width": 0}, "slow");

    $('.slide').removeAttr('current');
    next.attr('current', "1");

});

Answer №3

I made adjustments to your HTML code by adding the classes "current" and "page". Here is the updated HTML:

<div class="scroll">
   <div class="buttons">
       <a id="prev">prev</a>
       <a id="middle">test</a>
        <a id="nxt">next</a>
    </div>
    <div id="diva" class="current page">div AA</div>
    <div id="divb" class="page">div BB</div>
    <div id="divc" class="page">div CC</div>
</div>

Please update your JavaScript code as follows:

$(document).ready(function() {
   $('#nxt').click(function() {
    var $cur = $('.current');
    var $next = $cur.next();
    if ($next.length == 0) 
       return false;

    $cur.removeClass('current');
    $next.addClass('current');

    $('.page').not('.current').animate({"width": 0}, "slow");
    $('.current').animate({"width": 200}, "slow");
  });

  $('#prev').click(function() {
     var $cur = $('.current');
     var $prev = $cur.prev('.page');

     if ($prev.length == 0) 
       return false;

     $cur.removeClass('current');
     $prev.addClass('current');

     $('.page').not('.current').animate({"width": 0}, "slow");
     $('.current').animate({"width": 200}, "slow");
  });
 });

You can view a working demo here.

I hope this helps! :)

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

Update an existing item or add a new one if it is not already present

I am attempting to create a functionality similar to canva.com, where users can select images from the sidebar and drop them anywhere in the "div", allowing multiple images with individual positions. However, when I use setState(prevState=>{return [...p ...

Is there a way to bring together scrolling effects and mouse movement for a dynamic user

If you want to see a scrolling effect, check out this link here. For another animation on mouse move, click on this link(here). Combining both the scrolling effect and the image movement might seem challenging due to different styles used in each templat ...

AngularJS - Create Alert Pop-Up for Missing Input Fields

I've been struggling to set up my app so that it displays an alert when the user attempts to submit a form with an empty input box. Despite having a confirmation popup working in another part of the application, I can't seem to figure out why thi ...

Using Angular Ionic for a click event that is triggered by a specific class

I am utilizing Highcharts and would like to click on the legend upon loading. With the use of Angular Ionic, how can I trigger a click on the .highcharts-legend-item class within the ngOnInit() {} method? I am aiming to click on this class as soon as the ...

Is there a way to include the site_path define('SITE_PATH','http://127.0.0.1/project/'); in a jQuery URL?

Looking for help with my jQuery Ajax code jQuery.ajax({ url:'login.php', }); I am trying to figure out how to add a site path in the url like we define a site path in PHP using define('SITE_PATH','http://127.0.0.1/project/&apos ...

How can I display a calendar with a complete month view using ng-repeat?

I was trying to replicate a table similar to the one shown in this image: (disregard the styling). I am struggling with how to properly format the data to create a similar table in HTML. $scope.toddlers = [ { "name": "a", "day": 1, "total": 3 }, { ...

Iterate through the xml.documentElement in a loop

I want to show 8 men and 2 women in SVG format. However, my current function only displays one man and woman. How can I add a loop to make this work for all individuals? for (i = 0; i < Serie[n].Number; i++) { return xml.documentElement } The data arr ...

"Using JavaScript to trigger a button click event, and then

I have a question that I think may sound silly, but here it is. I have this code snippet: <script type="text/javascript"> $(document).ready(function(){ var email_value = prompt('Please enter your email address'); if(email_value !== null){ ...

Is there a way to invoke a function using $scope within HTML that has been inserted by a directive in AngularJS?

After moving the following HTML from a controller to a directive, I encountered an issue where the save button no longer functions as expected. I attempted to change the ng-click to a different function within the directive code, and while that worked, I u ...

Is it possible to incorporate a 960 grid system into a div container?

Can I contain an entire 960 grid within a div on my webpage? I am looking to create a page wider than 960px, and considering placing sidebars outside of the 960 grid while having it manage the central column. ...

Learn how to utilize the combineLatest/zip operators to only respond to emissions from the second observable while disregarding emissions from the first observable

Here's an example of how I'm initializing a property: this.currentMapObject$ = zip(this.mapObjects$, this.currentMapObjectsIndex$, (mapObjects, index) => mapObjects[index]); I want the value of this.currentMapObject$ to be emitted only ...

Tips for creating precise dots on a polished slideshow

Is it possible to change the buttons on my slideshow to actual dots instead of numbers? I tried following the instructions I found online, but the code doesn't seem to be working. Can anyone provide guidance on how to achieve this? My website is still ...

Having trouble converting JSON into a JavaScript object

I am encountering an issue with my HTML box: <span>Select department</span><span> <select id="department" onchange="EnableSlaveSelectBox(this)" data-slaveelaments='{"a": 1, "b": "2& ...

The resizing of the window does not trigger any changes in the jQuery functions

Here is a snippet of jQuery code that executes one function when the window size is large (>=1024) and another when it is resized to be small. Although the console.logs behave as expected on resize, the functions themselves do not change. This means that ...

javascriptcode to execute before loading google maps

I am facing an issue with displaying markers on Google Maps. The problem arises when the array with latitude and longitude values is constructed through an Ajax request. Due to the map being loaded before the initialization of the array, I am unable to see ...

How to position an absolute element beneath a fixed element

My website is experiencing a problem where the fixed header is overlapping an absolute paragraph on this page. Does anyone know how to resolve this issue? ...

The grid elements are not in perfect alignment

I'm having trouble aligning the <p> element to the left and the image to the right. The image is not aligning properly with the fourth column, so I need to figure out how to fix that. .content{ display: grid; grid-template-columns: 25% 25 ...

What are some strategies for preventing unused setState functions in React? Is it possible to create a React useState without a setter function

Currently working on reducing or eliminating npm warnings related to the React site. Many of these warnings are due to the setState function, which is marked as 'unused' in the code snippet below. const [state, setState] = useState('some st ...

I am a newcomer to Stack Overflow and I am facing difficulty in getting my form to submit successfully

Excuse any errors as I am new to this. I am facing an issue where my form is not submitting anything in the console. Could it be because my entire HTML file is within a return statement from a JavaScript function? I assumed it would work since I imported a ...

JavaScript string: Use regex to find and replace with position index

I'm not very familiar with regex, so I'm curious about the process of replacing a section in a string based on a regex pattern where the index is part of the identified section. Let's consider this example string: let exampleStr = "How do ...