Scrolling through UL elements using Jquery

I am struggling to implement jQuery for scrolling a UL list, with two span elements for moving up and down. It works fine for a single li child, but how can it work for a dynamically filled ul? Any help would be greatly appreciated, as I am completely lost.

 $('span.scrollDown').click(function () {
        $('.liste-grostitres li:first-child').css('margin-top', 0 - $('.liste-grostitres li').outerHeight());
        $('.liste-grostitres').css('overflow', 'hidden');
    });

    $('span.scrollUp').click(function () {
        $('.liste-grostitres li:first-child').css('margin-top', 0);
        $('.liste-grostitres').css('overflow', 'visible');
    });


<div id="grostitres">
    <div class="gInner">
    <span class="scrollUp"></span>
    <span class="scrollDown"></span>
    <div class="scrollable" id="divlist" runat="server">   
      <ul>
          <li></li>
          <li></li>
          ...
      </ul>
    </div>              
    </div>

Answer №1

Check out this fiddle demonstrating slideToggle functionality: http://jsfiddle.net/RMQLM/

Here is the code snippet:

HTML:

<div id="up">up</div>
<div id="list">
<ul>
    <li>foo1</li>
    <li>bar1</li>
    <li>foo2</li>
    <li>bar2</li>
    <li>foo3</li>
    <li>bar3</li>
    <li>foo4</li>
    <li>bar4</li>
    <li>foo5</li>
</ul>
</div>
<div id="down">down</div>

CSS:

div#list {
    height: 93px;
    overflow: hidden;
    border: 1px solid red;
}

jQuery:

var listcount = $('li').size();
var cli = 1;
$('#down').click(function() {
    if (cli < listcount) {
        $('li:nth-child(' + cli + ')').slideToggle();
        cli++;
    }
});
$('#up').click(function() {
    if (cli > 1) {
        cli--;
        $('li:nth-child(' + cli + ')').slideToggle();
    }
});

Answer №2

To set your unordered list (UL) element to be relatively positioned, add the following CSS: position: relative; and top: 0;.

Implement a function to manage the scrolling animation:

var scrollUL = function(offset) {
    // Select the UL element to be scrolled
    var toScroll = $('#divlist').find('ul');

    // Determine the distance to scroll (assuming all list items are of equal height)
    var scrollDistance = $('#divlist').find('li').outerHeight(true);

    // Perform the animation
    toScroll.stop().animate({ top: '-=' + (offset * scrollDistance) });
};

Update your click event handlers to trigger the scrolling function like this:

$('span.scrollDown').click(function() {
    scrollUL(1);
});

$('span.scrollUp').click(function() {
    scrollUL(-1);
});

If you notice irregular scrolling distances when repeatedly clicking the scrollDown or scrollUp buttons, consider using jQuery's .one() method.

Answer №3

In my opinion, optimizing the animation process could involve animating the entire UL element instead of each individual LI. Considering that the UL is already contained within a DIV, it makes sense to animate the UL in relation to its wrapper. This approach would achieve the same effect as animating a single LI within the UL, eliminating the need to create a new solution from scratch.

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 complete enclosure within the brackets

I am trying to enclose a div with text inside in brackets. I want the entire text (the div) to be surrounded by brackets. Here is an example of what I am looking for: https://i.sstatic.net/k4QRF.png I considered using border properties like top, bottom, ...

Combining Two Ajax Forms

I currently have two Ajax forms that filter posts separately on the same page of my WordPress website. They are functioning well individually. For reference, here is the link to the Test Server: Test Server My goal now is to combine these two Ajax form ...

Script execution is disabled on this system preventing the loading of content - ANGULAR V14

Every time I try to run my Angular project or any ng command, I keep encountering the following error message: ng : File C:\Users\achra\AppData\Roaming\npm\ng.ps1 cannot be loaded because running scripts is disabled on this ...

Contrasting date and time components within a JQuery date time picker

Utilizing Jquery, I have implemented two date time pickers. Upon clicking the show button, I require the difference between the two dates to be displayed in the textbox identified as result. For example: Time1 = 04/30/2014 10:27 am Time2 = 05/01/2014 1 ...

A guide on dynamically accessing an image from the src directory using props in a Vite + React application

export default function Card(props) { return ( <card> <img className={cardCss.card__img} src={`../assets/imgs/card/${props.img}`} alt="" /> <div className={cardCss.card__stats}> ...

Warning: React has reached the maximum update depth limit

I am currently developing a D3 chart using React. Within my chart, I have integrated a brush component that interacts with React Hooks. Here is the snippet of code I am working with: App.js import React, {useEffect, useState} from 'react'; impo ...

What is the best way to utilize a color picker to apply CSS color to a parent element?

When the pencil glyphicon is clicked, a color picker appears. I only want to apply the selected color from the color picker to the list elements that are the grand parent of the pencil glyphicon. Here's a snippet of my Ruby front-end code: <% cat ...

Sending a collection of objects from an Ajax call to a WebMethod

My objective is to transfer data from a form to a WebMethod. I aim to fill the UseInfo object with form data and also populate certain properties added to the NewUser class passed through the ajax request. Passing the UserInfo as an input parameter result ...

Does 1 CSS point amount to the same as 75% of a CSS Pixel?

Can anyone help clarify the relationship between CSS pixels and CSS points in modern web design? I've come across information stating that one CSS point is equivalent to 3/4 of a pixel. Is this accurate? Also, is it true that we can disregard the old ...

Is there a discrepancy in performance when running a function on an individual element versus a group of elements within jQuery?

Imagine having the choice between applying a function to an individual DOM element or a list of them: For Individual Elements: $('#element1').click(function () { $(this).hide(); return false; }); $('#element2').click(functi ...

The function button.click() is not compatible with Internet Explorer 11 and will not

I have implemented a jqx menu using the code snippet below: <ul style='width: 200px;'> <li onclick="logOffButton.click();">Sign off</li> </ul> My goal is to automatically trigger a click event on the "logOffButton" o ...

What is the reason for restricting AJAX requests to the same domain?

I'm puzzled by the limitation of AJAX requests to the same domain. Can you explain the reasoning behind this restriction? I don't understand why requesting files from external locations is an issue, especially since servers making XMLHTTP reques ...

AngularJS service failing to deliver promised result

I am in the process of retrieving data from my database using AngularJS. I have created a service to fetch the data and a controller to display it. Check out my code snippet: angular.module('myApp') .factory('panelService', [&apos ...

Utilizing Aramex API in React Native: A Step-by-Step Guide

Currently, I am tackling an eCommerce venture that requires the utilization of Aramex APIs for shipping and other functionalities. Since my project is being developed in React Native, I am seeking guidance on how to integrate Aramex APIs into this framewo ...

Is it possible to utilize npm packages within a standard web page without any frameworks or libraries?

I am currently working on a basic website created using vanilla HTML, CSS, and JS files. My goal is to incorporate the import { moment } from "moment" syntax into my JS files. However, after adding npm to my project, installing moment with npm i ...

Find the position of the object in a list

I have an array that looks something like this data: Array(3) 0: data: Object account_id: (...) address_1: (...) address_2: (...) amount: 10.00 id: 1234 ... 1: data: Object account_id: (...) address_ ...

Unable to view iframe content within jQuery dialogue in Internet Explorer as only a blank dialogue box is appearing

$(function(){ var settings = { autoOpen: false, modal: true, show: 'slide', resizable: false, width: 800, height: 700 }; $('#dialog').append(iframe).appendTo(" ...

The module cannot be required as a function for calculating the area of a square

None of the functions I created seem to be working properly. Take a look at this example function: function calculateArea(side) { var area = side * side; return area; } When I attempt to use the module using require, like so: var formulas = require( ...

There seems to be confusion surrounding the $.isArray() function in jQuery

I'm currently trying to determine whether the p array is valid or not. I'm not sure if I'm on the right track or if I'm making a mistake. I am currently studying the jQuery.isArray method. I suspect that there may be an error in my code ...

Focusing on the active element in Typescript

I am working on a section marked with the class 'concert-landing-synopsis' and I need to add a class to a different element when this section comes into focus during scrolling. Despite exploring various solutions, the focused variable always seem ...