Div that scrolls only when children can be displayed without overflowing

I am seeking a solution to ensure that the children inside my scrollable div are only visible in their entirety.

HTML

 <div id="container">
      <div class="child"></div>
      <div class="child"></div>
      <div class="child"></div>
      <div class="child"></div>
      <div class="child"></div>
      <div class="child"></div>
 </div>

CSS

 #container {
      display:block;
      overflow-y: scroll;
      overflow-x: hidden;
      height: 250px;
      width: 150px;
 }
 .child {
      background-color: red;
      height: 100px;
      width: 100px;
      margin: 5px;
 }

In this scenario, only two and a half red boxes will initially appear on the screen (the third box extends beyond the viewable area). I aim for the third (and subsequent) boxes to be shown only when they can be fully displayed by scrolling.

Answer №1

If you want to control the opacity of an inner element based on its position, you can use JavaScript to check the bounding rectangle. If the element is inside, you can set its opacity to 1.

var children = document.getElementsByClassName("child");
var container = document.getElementById("container");

for(var i = 0; i < children.length; i++) {
    children[i].classList.add('donotshow');
    if(children[i].getBoundingClientRect().top > container.getBoundingClientRect().top && (children[i].getBoundingClientRect().top + children[i].getBoundingClientRect().height < container.getBoundingClientRect().top + container.getBoundingClientRect().height)) {
        children[i].classList.remove('donotshow');
    }
}

container.addEventListener("scroll", function() {
    console.log("hi");
    for(var i = 0; i < children.length; i++) {
        children[i].classList.add('donotshow');
        if(children[i].getBoundingClientRect().top > container.getBoundingClientRect().top && (children[i].getBoundingClientRect().top + children[i].getBoundingClientRect().height < container.getBoundingClientRect().top + container.getBoundingClientRect().height)) {
            children[i].classList.remove('donotshow');
        }
    }
})

Check out this JSFiddle for a working example!

I hope this solution helps you with your project.

--Best regards

Answer №2

You have the option of utilizing the Intersection Observer API along with a polyfill for it

Check out this basic working demonstration:

let children = Array.from(document.querySelectorAll('.child'));

let options = {
    root: document.querySelector('#container'),
    rootMargin: '0px',
    threshold: 1.0
}

let callback = function(entries, observer) { 
        entries.forEach(entry => {
        entry.target.style.visibility = (entry.intersectionRatio == 1) ?
'visible' : 'hidden'            // the Element whose intersection with the intersection root changed.
    });
};

let observer = new IntersectionObserver(callback, options);

children.forEach(child => observer.observe(child));
 #container {
      display:block;
      overflow-y: scroll;
      overflow-x: hidden;
      height: 250px;
      width: 150px;
 }
 .child {
      background-color: red;
      height: 100px;
      width: 100px;
      margin: 5px;
 }
 <div id="container">
      <div class="child" id="child1"></div>
      <div class="child" id="child2"></div>
      <div class="child" id="child3"></div>
      <div class="child" id="child4"></div>
      <div class="child" id="child5"></div>
      <div class="child" id="child6"></div>
 </div>

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

Utilizing the Strength of Code Snippets and the Art of Style Sheet Separation

When it comes to developing beautiful web pages and forms from scratch, I often struggle as the end result tends to be quite unappealing. Luckily, there are numerous CSS code snippets available that offer stunning solutions. Currently, I am delving into py ...

What could be causing my Angular.js application to malfunction on IE7?

I have developed an Angular.js application that is working well on most browsers, but I am now facing compatibility issues with IE 7 and above. I have tried different approaches such as adding id="ng-app", using xmlns:ng, manually bootstrapping angular wi ...

Is there a way to generate a distinctive curved design using CSS for a

I am currently using CSS and div elements in an attempt to create these particular lines: https://i.stack.imgur.com/Ytowq.png .line { width: 1px; height: 100px; background-color: black; position: absolute; border-radius: 50%/100px 1 ...

Implementing a Popover Notification When Clicked

I'm a beginner at this. I came across an example of a popover message box in the link provided below. I attempted to implement it, but for some reason, it's not working. Could I be overlooking something? Alternatively, is there a simpler way to ...

Is it possible to cache an html page and display it on the current page when reloading?

I have been attempting to design a webpage with links in a table that trigger modals when clicked. These links are added dynamically using Jquery. $("table").append('<tr><td><a href="#exampleModal" data-bs-t ...

Localhost Delay in XAMPP

As I work on developing my own website, I have opted to use XAMPP for hosting. After making modifications to the CSS, HTML files, and replacing the existing images with new ones in the designated folder, I encountered an issue. Despite restarting and re-i ...

Reorganize div elements responsively using Bootstrap 5.0

Struggling with web design using HTML, CSS, and Bootstrap v5.0, I am facing an issue. I have three divs A, B, and C that I want to reorder responsively as shown in the image below. A consists of a h2 and p tag, B includes two buttons, and C displays an ima ...

Ways to dynamically update a div with data from a JSON response

I'm currently in the process of developing a search platform. I have three static divs on the search results page that display certain content, all containing similar code. For example: <div id="result" class="card"> <img src="hello.png" ...

The cloned rows created with jQuery are failing to submit via the post method

Hello, I am currently working on a project in Django and could use some assistance with my JavaScript code. Specifically, I am trying to incorporate a button that adds new rows of inputs. The button does function properly as it clones the previous row usin ...

What is the proper way to retrieve this stylesheet and add it to the header of my HTML file?

I want to utilize a style sheet from Wikipedia. However, when I fetch the style sheet and attempt to pass the URL retrieved through AJAX to the head of my HTML document, the URL behaves unexpectedly. Initially, I tried to use the fetched URL directly: var ...

Looking to tally up the variety of items in Django?

Before, I had a table with a client summary list. One column showed object types and the other displayed the quantity of each object type. @login_required def client_summary(request, client_id): client = models.Client.objects.get(pk = client_id) i ...

Conceal optional navigation bar options once a user has logged in - utilizing Angular 8

I need assistance with hiding certain links in my navbar once a user has logged in. Below are the current navbar menus: <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav ml-auto"> <li class="nav ...

Ways to align elements vertically in a container without using flexbox?

I am working with a ul element that has a height of 270px and contains 10 li elements. My goal is to have all the li elements vertically justified, meaning the top and bottom li elements should touch the container's top and bottom respectively, while ...

Responsive HTML table with full width of 100%

I am attempting to make an HTML table responsive by setting the two td elements to occupy 100% width on smaller screens. This is what I have so far... .test1{ background:teal; text-align:center; padding:20px; } .test2 { background:tan; paddin ...

Identifying the Operating System and Applying the Appropriate Stylesheet

I am trying to detect the Windows operating system and assign a specific stylesheet for Windows only. Below is the code snippet I have been using: $(function() { if (navigator.appVersion.indexOf("Win")!=-1) { $(document ...

Is there a way to refresh my order hook in React JS?

I've been attempting to modify the values within my order hook, but for some reason, they aren't updating. I'm relatively new to React and can't figure out what mistake I might be making. Any insights? Take a look at my code snippet: ...

Retrieve the checkbox value and assign it to an object in the $scope of an Angular

As a newcomer to angularjs, I've been struggling with this code snippet for the past two days. My goal is to retrieve values from selected checkboxes within my angular js controller. I have experimented with both ng-true-value and ng-false-value, bu ...

CSRF token not recognized. Request cancelled. Even after including the CSRF token {% csrf_token %}, the error persists

I'm encountering an issue with the CSRF token being incorrect or invalid. I have included the {% csrf_token %} above my form, but I am still facing this problem. Can anyone assist me with this? Here is a snippet of my HTML file: <h4>regist ...

unable to submit Angular form via post method

I'm encountering an issue with the code I wrote in HTML. The error message says, "The page you are looking for cannot be displayed because an invalid method (HTTP verb) is being used." This is how my HTML code looks: <form name="payment" action ...

Center elements at % on the webpage using CSS styling

When creating two bars at 70% and 100%, I also want a small triangular shape to point specifically at the 70% mark. Here is how I am currently drawing the triangle: .arrowUp { width: 0; height: 0; border-left: 10px solid transparent; border-right ...