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

"An error was thrown due to an illegal invocation while utilizing $.post, although $.ajax seems to be

I've been experimenting with FormData to send data to a different URL, but the code below doesn't seem to be working $("form").on("submit", function(e){ e.preventDefault(); var formData = new FormData(this ...

What is the process for integrating npm packages with bower?

Currently, I am immersing myself in the realm of ember using a grunt/bower workflow. I have noticed that a lot of the ember extensions are available on github as npm packages. Can anyone provide guidance on the most effective approach for incorporating th ...

Obtaining the width of a child table using Jquery

I have a question that might seem simple, but I can't figure it out. How can I use jQuery to get the width of a table that is a child of a div with the class "test"? <div class="test"> <div id="one"> </div> <table> <thead&g ...

When the property "a" is set to true, it must also require the properties "b" and "c" to be included

I'm looking for a way to modify the following type structure: type Foo = { a: boolean; b: string; c: string; } I want to change it so that if a is true, then both b and c fields are required. However, if a is false or undefined, then neither b ...

Incorporating a for loop, ExpressJS and Mongoose repeatedly utilize the create method to generate

When users input tags separated by commas on my website, ExpressJS is supposed to search for those tags and create objects if they don't already exist. Currently, I am using a for loop to iterate through an array of tags, but only one object is being ...

What could be causing the background color opacity of the HTML hr tag to decrease?

I am trying to modify the height and background color of the <hr> HTML tag. However, even though the height and color are changing, it appears that the background color opacity is decreasing slightly. What could be causing this issue? Here is my cod ...

Using Rails and ajax to dynamically choose where a partial should be rendered

In my html template, I have a loop statement generating multiple divs and buttons with unique ids. The resulting code resembles the following... // index.html.erb <button id="button-town-data1"><%= link_to 'Load Details', town_path(curr ...

Searching for all choices within a select dropdown using Selenium and Python

There's a website called noveltop (.net) that hosts web novels, and on each chapter page, there is a dropdown menu where you can select the chapter you want to jump to. I've been using Selenium with Python and the Firefox (or Chrome) driver to e ...

Do you always need to use $scope when defining a method in Angular?

Is it always necessary to set a method to the $scope in order for it to be visible or accessible in various parts of an application? For example, is it a good practice to use $scope when defining a method that may only be used within one controller? Consid ...

Issue with Material-ui Autocomplete: onChange event not firing when value is updated in onHighlightChange

I have been customizing Material UI's Autocomplete by adding a feature that allows users to move options to the input using keyboard events (Arrow keys up and down). Then, the user should be able to select an option by pressing the ENTER key. I am fa ...

Converting HTML to PDF using AngularJS

Can anyone help me with converting HTML to PDF in Angular? I have tried using the angular-save-html-to-pdf package from npm, but encountered errors. Are there any other solutions or custom directives available for this task? ...

Looking for assistance with an Angular2 post request?

I'm having an issue with a post request to obtain a token granting access to another access token. Each time I attempt to make the post request, I encounter an error stating that the access_token property is trying to read something undefined. It seem ...

Arranging a div's position in relation to an unrelated div

I need to position a div element called "a" below another div element known as "b". The HTML code has the following structure: <div id="a"></div> <form> <div id="b"></div> <div id="c"></div> </form> U ...

Looking to locate the child div elements within a parent div

I am having trouble determining the individual lengths of child divs within parent classes that share the same name. For example: <div class="main-div"> <div class="parent"> <div class="child"></div> <div class= ...

Switching images with the hover effect using jQuery

I am attempting to dynamically change a down arrow image with jQuery on hover. I have explored using CSS background-image solutions, but my current setup already has a background in place. While I have come across similar questions before, I haven't ...

Creating a Vue.js component with dynamic data

Recently, I started working with Vue.js and have been experimenting with it for a few days. One of the challenges I'm facing is trying to dynamically add a new div element with text input every time the enter button is pressed. I would greatly appreci ...

The MuiThemeProvider.render() function requires a valid React element to be returned, or null if necessary

I am working on creating a dropdown using Material UI and React. It renders perfectly when the dropdown component is in my src/app.js, but I encounter errors when I move it to a separate file named fruits.js: MuiThemeProvider.render(): A valid React el ...

What is the best way to limit the top margin for a fixed element?

Recently, I came across this code snippet: jQuery(document).ready(function($){ $( window ).scroll(function() { var current_top = $(document).scrollTop(); var heights = window.innerHeight; document.getElementById("sHome").styl ...

Restricting the length of dynamic dropdowns in a React application

Click here to view the code on CodeSandbox My dropdown menu options are dynamically generated and filtered based on custom data. const dropdownData = [ { code: "others", name: "Others", amenity: [] }, { code: "bed", name: "Bed", ...

Only the initial upload file is being passed through the Apollo Express server, with the remaining files missing in action

Currently, I am utilizing the apollo-express server with GraphQL. One issue I am encountering involves a mutation where I pass files from the front-end to the back-end. Strangely, I receive the file:{} object only for the first file - for the others, I rec ...