What is the best way to incorporate a <li> view cap within a div element using JavaScript?

Currently, I am attempting to implement a dynamic <li> view limit within the content of a div. My goal is to display only 3 <li> elements each time the div content is scrolled.

Although not confirmed, I believe this example may be helpful:

Answer №1

Outdated Response

Is this what you're looking for? http://jsfiddle.net/bennwbpu/1/

$(function(){
    var liheight = $(".demo2 li").outerHeight();
    $(".demo2").outerHeight(liheight*3);
})

We first determine the outer height of a single <li> and then we set the outer height of .demo2 to three times that value.

If you want the scroll position to snap to the top of the closest <li> whenever there is a scroll event, you can check out:


Updated Answer

Fiddle link: http://jsfiddle.net/bennwbpu/7/

This solution may seem lengthy, but it was crafted through a combination of research and experimentation.

Streamlined approach

$(function(){
    var lih = $(".demo2 li").outerHeight(),
        lst = 0,
        f=0;
    $(".demo2").outerHeight(lih*3).scroll(function(e){
        var $this = $(this),
            st = $this.scrollTop();
        function _scroll(n) {
            $this.css("overflow","hidden").stop().animate({scrollTop:lst+(n)*lih*3}, 500, "swing", function(){setTimeout(
                function(){                    
                    $this.css("overflow","auto");
                    setTimeout(function(){f=0},50);
                },500)
            })
        }
        if (!f) {
            f=1;
            if (st > lst)
                _scroll(1);
            else
                _scroll(-1);
       }
       lst = st;
    });
})

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

Linkify Method appearing in html.erb file displaying with HTML on the view

Apologies if this question seems basic, but I am encountering an issue when calling the following method on the @page instance variable. The view is displaying HTML tags instead of the desired content... module PagesHelper def linkify_page page rege ...

Tips for extracting text from a selenium webelement icon that displays hovertext

Let's use Amazon as an example. Suppose we want to extract the star rating for a product. When hovering over the stars, we see a text element that says "4.0 out of 5 stars" and upon inspecting the code, we find: <span class="a-icon-alt">4.0 ou ...

A step-by-step guide on how to exclusively print items that have been selected using a checkbox in AngularJS

I have created two tables and added a checkbox for each one. Instead of default checkboxes, I have used images that change when clicked. Here is the code snippet: <button class="btn btn-lg btn-customPrint-md no-print" ng-click="checkBoxPrint2 = !check ...

Triggering a JavaScript function when a page is focused due to user interaction

In my project, I have a specific requirement that involves triggering a new window to open when the user clicks on an icon. In this new window, the user should be able to view and edit certain fields. Upon closing the new window and returning to the parent ...

Is there a way to find all records created at a particular time daily through a query?

I understand how to search for documents within a particular range, but I am unsure of the query needed to retrieve all documents in a collection that were created at 3PM. Assuming there is a field called createdAt where this information is stored as Jav ...

Click to remove the ellipsis from the backbone

Some Background Info I am working on creating a feed similar to Twitter where each row expands on click to show more information. The data is fetched from a JSON file sent from the backend to the frontend, and I am using Backbone.js for rendering. My fee ...

Running a code from a plugin in Wordpress site

I am currently utilizing the "wp-video-lightbox" plugin for WordPress, which generates small floating boxes for my videos. I am interested in incorporating variables like http://www.example.com/?video3 to provide shortcuts similar to what YouTube offers. ...

What steps can be taken to enhance the responsiveness of this Bootstrap 4 code?

I've been trying to make this code more responsive, but I haven't found a suitable solution yet. When the browser window shrinks to mobile sizes, the list becomes too narrow and the picture/video items on the right end up small and aesthetically ...

Issue with Firefox causing problems with smooth scrolling Javascript on internal links

I recently created a one-page website using Bootstrap. The navigation menu items are internal links that point to different sections within the page, and I added some smooth scroll JavaScript for a more polished scrolling effect. While the website functio ...

How about implementing a 'thumbs up' feature on every post?

I'm relatively new to SQL and PHP and have successfully set up a database where I can input entries through an HTML form. However, I am struggling with implementing a 'like button' feature that will increment a counter for each specific post ...

The MongoClient object does not possess the 'open' method

I recently started working on a project using Node.js, Express.js, and MongoDB. I've encountered some issues while trying to set up the database configuration. Below is a snippet of code from my index.js file: var http = require('http'), ...

Explore the versatility of jQuery by utilizing multiple objects in your POST and GET requests to PHP for enhanced

I am trying to send multiple arrays to a PHP page using jQuery and retrieve results, but I am encountering an issue where the array values are not being properly passed to the PHP page. Notice: Undefined index: $name Notice: Undefined index: $type Notice ...

Resizable item within a text box (similar to an HTML editing tool)

After extensive searching online, I have not been able to find a solution. What I need is a draggable input element within a textarea in a text-editable div. The draggable textarea should be integrated seamlessly into the text, and upon submitting, it shou ...

Issue with event listener not functioning properly with dynamically created content using AJAX (only using vanilla JavaScript

I used pure javascript AJAX to dynamically load content into the "test" div. However, when I try to click on a child div at index 6, an alert box is not being displayed as expected. How can I fix the issue with the click event not working? The gets functi ...

Retrieve all elements from JSON using jQuery

JavaScript: function loadDoc(url) { $.ajax({ url: 'mytestjson', dataType: 'json', cache: false }).success(function (result) { console.log(result); //var txt = result.newBranches[0].newNon ...

Having trouble with accessing the upvote/downvote input within a Django template

Currently, I'm trying to retrieve upvote/downvote data from a Django template in the following manner: <form method="POST" action="{% url 'vote' %}" class="vote_form"> {% csrf_token %} <input type="hidden" id="id_value" name="valu ...

After executing webpack, it has been noticed that one of the dist files consistently ends up empty

As someone who is new to webpack, I have successfully used the quick start guide to process a simple JS file from src to dist. Everything was working fine. However, I encountered an issue when trying to process more than one JS file. The original tutorial ...

How to Retrieve JSON Object Using Dynamically Generated String in Angular

Creating a controller in Angular involves retrieving URL parts and parameters using $statePrams. The $http service is then called to retrieve data from a JSON file. Once the data is received, the content of a specific object element - determined by $state ...

Having trouble accessing an element using jQuery(idOfElement) with a variable as the name parameter

Possible Duplicate: Issue with JavaScript accessing JSF component using ID Whenever I attempt to retrieve an element by passing a variable in jQuery(idOfElement), it doesn't work. But if I use something like jQuery('#e'), it works perfe ...

What is the best method to verify the presence of jQuery on a webpage using Python/Selenium WebDriver?

Our in-house automated testing framework is built using Selenium Webdriver in Python, with a mapping system linking object names to identifiers on webpages. However, we are encountering issues due to not waiting long enough for AJAX calls to complete, caus ...