jQuery can add scrolling buttons to a webpage

I have been trying to create a list that can be scrolled through by using buttons, while also having a visible and functional scrollbar. However, I am struggling to edit my code in a way that allows both features to work simultaneously. It seems like I can only get either the buttons or the scrollbar to function properly, but not both at the same time. Can anyone offer some assistance with this issue?

var itemsToShow = 3;

$('#scroll>li').each(function(i,k) {
    var ele = $(this);
    $(ele).attr('id', 'scroll' + i);

});


$('#up').bind('click', function() {
    if ($('#scroll0:hidden').length > 0)
    {
        // This means we can go up
        var boundaryTop = $('ul li:visible:first').attr('id');
        var boundaryBottom = $('ul li:visible:last').attr('id');

        if ($('ul li#'+ boundaryTop).prev().length > 0)
        {
            $('ul li#'+ boundaryTop).prev().show();
            $('ul li#'+ boundaryBottom).hide();
        }
    }
});

$('#down').bind('click', function() {
    if ($('#scroll li:last:hidden').length > 0)
    {
        // This means we can go down
        var boundaryTop = $('#scroll li:visible:first').attr('id');
        var boundaryBottom = $('#scroll li:visible:last').attr('id');

        if ($('#scroll li#'+ boundaryBottom).next().length > 0)
        {
            $('#scroll li#'+ boundaryBottom).next().show();
            $('#scroll li#'+ boundaryTop).hide();
        }
}
});
.lg {
    overflow-x:auto; 
    height:90px;
    overflow-y:auto;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul class="lg">
  <li>Text</li>
  <li>Text</li>
  <li>Text</li>
  <li>Text</li>
  <li>Text</li>
  <li>Text</li>
  <li>Text</li>
  <li>Text</li>
</ul>

<div id="updown">
  <a class="btn btn-primary" id="up" href="#">up</a>
  <a class="btn btn-primary" id="down" href="#">down</a>
</div>

I'm feeling a bit stuck here. Could someone please guide me on what I might be doing incorrectly? Your help would be greatly appreciated!

Many thanks in advance!

Answer №1

Learn how to scroll to the top and bottom with this simple code:

Check out this JSFiddle link for a live demo

// Scroll to the top
$('a#up').on('click', function(){
   $('.lg').animate({ scrollTop: 0 }, 600);
})
// Scroll to the bottom
$('a#down').on('click', function(){
   $(".lg").animate({ scrollTop:$(document).height()}, 600);
})

Answer №2

The scrollTop() function in jQuery is a handy one-liner to achieve this task.

Adjust the number 10 according to how many pixels you want to move up or down on the page.

$('#up').click(function(){
  $('ul.lg').scrollTop($('ul.lg').scrollTop()- 10);
});

$('#down').click(function(){
  $('ul.lg').scrollTop($('ul.lg').scrollTop() + 10);
});

Answer №3

Instead of physically showing or hiding fields, consider adjusting the scrollTop position of the scrollable div using JavaScript. This way, you can avoid removing them from the browser's flow and manipulate elements inside more efficiently.

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

Using the THIS keyword in JQUERY for functions without an action: a guide

Is there a way to dynamically set the widths of table elements based on their parent's data-attribute value? For example, if a parent has percent="10", I want the child element to have a width of 10%. How can this be accomplished? To illustrate, here ...

Using Angular to bind the ngModel to a variable's object property

In my application, I am working with a user object that looks like this: let user = {name: "John", dob:"1995-10-15", metadata: {}} The metadata property of the user object is initially empty. I want to add a new property to the metadata object based on u ...

The website link cannot be seen on Internet Explorer 8, however it is visible on other browsers like Firefox and Chrome

Please verify the following link: The link "Return to login page" is displayed correctly on Firefox, Chrome, etc., but it appears higher on IE8. How can this be fixed? To resolve this issue, you can adjust the CSS for the 'lost_password' div as ...

Plugins for Jquery validation, such as those for verifying files and handling dynamic form fields

Using ng-repeat in AngularJS, I am generating dynamic form elements that include file upload fields. I'm looking for a plugin to help me validate these fields. Can anyone recommend one? ...

Is it possible to incorporate a YouTube video into a webpage without displaying any external links to YouTube above the video player?

Looking for a solution to embed a YouTube video on my webpage without the link appearing when hovering over it and without the suggested videos at the end. Just the option to replay the video without the distraction of related videos. ...

Other than the doctype declaration and the opening html tag, what additional markup can reside outside of the head and body elements in an HTML document

When it comes to an HTML document, the majority of content is typically found within the html head and body. However, what other elements can exist outside of these sections? ...

Encountered an Xpath error while attempting to create a random email generator using Selenium IDE

While attempting to execute a script, I encountered an "element not found" error with Selenium failing to detect the xpath. My goal is to randomly generate email addresses. Every time there is an error message stating: [error] Element .//[@id='GmailA ...

The CubeCamera function is encountering an issue where it is unable to access the 'up' property due to it being undefined

After a long time, I revisited my three.js project and was reminded of the days when I used to type out the full name PlaneBufferGeometry. The project features several vehicles that are supposed to reflect their environment (and each other) through the use ...

Transmitting form data inputted by the user to a modal that resides in the same component, all without the need for child or parent components or

In need of a solution where users can input answers to questions and have all the entered data displayed in a popup alongside the respective question. If a user chooses not to answer a question, I do not want that question or any related information to be ...

Position the center button evenly between two images, aligned vertically using percentages

I'm attempting to achieve a specific layout that includes images scaling across Bootstrap breakpoints and a static button position. The challenge is maintaining the layout as depicted in the mockup, regardless of image size. The images are set to im ...

Spin the text within a div by 90 degrees and align it to the right side

I have been attempting to create an information box that contains a simple info text div. On the right side of this info box, I want to include a text labeled "more info" within a nested div to signify that the info box is interactive. To save space, I wou ...

obtaining Json format from an array: a comprehensive guide

Hey there, I am looking to convert my array into JSON format. Currently, my array structure looks like this: Array[0] abc: Array[1] 0: "English" length: 1 abc1: Array[2] 0: "English" 1: "Urdu" length: 2 Here is the structure that I want in JSON using Jav ...

Show a selected checkbox within a form for submitting via POST method

I am in need of assistance with a wizard that should display the previously posted value. index.html <form method="post" action="posted.php"> <input type="text" name="surname" value="" placeholder="Surname" /> <input type="text" name="firs ...

Ways to adjust the content width within an iframe without altering the iframe's overall width

I need help with adjusting the width slider in my iframe. I want the width slider to control the content width within the iframe, not the actual width of the iframe itself. Essentially, I want to switch between mobile and desktop mode by resizing the con ...

Combine the serialized form data along with an array and post them together

I am encountering difficulties with sending the form through ajax. Along with the information input by the user, I also need to include an array of objects in the data being sent. AJAX POST: submitHandler: function (form) { $.ajax({ ...

Error: The query has already been processed:

I'm encountering an issue while attempting to update the document. The error message indicates that the query has already been executed. MongooseError: Query was already executed: footballs.updateOne({ date: 'January 4' }, {}) app.post(& ...

I'm really confused as to why I am receiving an undefined error in this code. Can someone please assist

I'm encountering an issue with getting undefined in this section of code. Is there a way to fetch the data using useEffect, and once everything is loaded, how can I efficiently store it in a useState variable and then display the necessary content? co ...

What is the best way to divide a string that includes commas into separate parts?

When splitting input strings by commas using .split(','), I encountered an issue with strings that contain commas within a single name. For example: "John, Smith". Typically, my strings appear like this: "Emily, Sasha Flora, Camille-O'neal" ...

Navigating State as a Fresh Path in Ionic Framework using Angular UI-Router

I am currently using the Ionic Framework along with its AngularJS UI-Router and $stateProvider to manage different views within my application. However, I am facing challenges in specifying to the $stateProvider that I have multiple "Main Views", each of ...

What is the best way to verify a user's login status in AngularJS using $routeChangeStart event?

I am new to AngularJS and I need help checking if my user is logged in or not using $routeChangeStart. Controller angular.module('crud') .controller('SigninCtrl', function ($scope,$location,User,$http) { $scope.si ...