Scroll through Two DIVs, where one is displayed and the other is concealed

Check out my JSFiddle here: https://jsfiddle.net/rq2tvccg/14/

I'm working on a project with 2 DIVs that each contain elements. Only one of the DIVs is displayed at a time, toggled by a button. I need to add an element that appears in both lists simultaneously. The Element's ID can be either List1_<Random> or List2_<Random>.

The problem arises when trying to scroll both DIVs to the newly added element. Due to one of the DIVs being hidden, scrolling using jQuery doesn't work as expected:

// Scroll to NEW for List 1
var elemAdded1 = $('#List1_' + id);
var pos1 = $(elemAdded1).position().top;
$("#list1").animate({scrollTop: pos1},1000); 

// Scroll to NEW for List 2
var elemAdded2 = $('#List2_' + id);
var pos2 = $(elemAdded2).position().top;
$("#list2").animate({scrollTop: pos2},1000); 

Is there a way to adjust the scrolling of both DIVs so that switching between them positions the view correctly?

Please note: The elements may vary in height between List1 and List2, so relying on visible element height won't work.

Answer №1

Experiment with your code using the opacity style option as well.

Here is a helpful JSFiddle link to test it out.

Answer №2

I proposed a solution to incorporate a container div that would calculate the total height of added items, allowing for accurate scroll offsets. Additionally, I utilized z-index to switch between two divs seamlessly. Feel free to test it out on this JSFiddle link

Implementing the Container

<div class="list" id="list1">
  <div>    <!-- Container for Height Calculation -->
    <li>Item 1.1</li> ...
  </div>
</div>

Utilizing Container Height for Scrolling

$("#list1").animate({
    scrollTop: $('#list1 div').outerHeight()
}, 1000);

Z-Index Toggle for Div Switching

.hidden {
    z-index: -1;
}

if ($('#list1').hasClass("hidden")) {
    $('#list1').removeClass("hidden")
    $('#list2').addClass("hidden")
}

I hope this solution is helpful! :)

Answer №3

To ensure that the lists are scrolled to the bottom (or to the last item in the list) when the 'add' button is clicked, you need to set the scrollTop value for both list containers.

For list1

$("#list1").animate({scrollTop: $('#list1 li:last-child').position().top},0); 

For list 2

$("#list2").animate({scrollTop: $('#list2 li:last-child').position().top},0); 

Check out the updated Fiddle here

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

What is the best way to find the difference between two time moments using Moment

Hello everyone, I could really use some assistance with Moment.js. I have two input fields, one labeled Start and the other labeled Stop. start = moment().format('LT'); // This works when I click on the play button stop = moment().format(' ...

What is the process of combining two class elements?

In my JavaScript class practice, I'm working on creating two users, each equipped with a weapon. My goal is to have a function within the class that allows the players to attack each other and decrease their health based on the damage of their respect ...

Tips for properly setting and accessing data objects in React when utilizing a Firebase database

I’m encountering issues with storing and retrieving data using the useState hook in React after fetching it from a Firebase database. The issue appears to be related to not all users having all values in the playerData data packet – for example, if a p ...

Analyzing a text file against a string to identify discrepancies using Node.js

Recently, I came across a dilemma involving a text file containing information on all Wifi connections (such as ssid, mac no, strength, etc.) that were within my laptop's range just 2 minutes ago. Now, I've rerun the code and obtained the current ...

Do not apply hover effect to a particular child div when the hover effect is already applied to the parent

I am encountering a problem with the hover effect. I have 3 child div's structured as follows: <div class="parent"> <div class="child1">A</div> <div class="child2">B</div> <div class="child3">C</div ...

What is preventing this Javascript from running in Firefox and Chrome?

I recently encountered an issue with some Javascript code that functions correctly in Internet Explorer, but fails to work on Mozilla Firefox or Google Chrome. Any insights as to why this might be the case? function returnData(strCode,strProgramCode,strNa ...

Reactjs button only responds on the second click instead of the first tap

Currently, I am working on a Reactjs/nextjs project and have a video with audio button on my page. There are two things that I want to achieve: 1) I would like the button to have the "bi bi-volume-mute" class by default instead of "bi bi-volume-down". 2) W ...

What is the reason that the reduce function is only effective when the final argument is explicitly stated?

I'm having trouble understanding the reduce method. What is the reason why const sumOfCubes = nums => nums.reduce((a,b) => a + Math.pow(b, 3)) does not function properly, while const sumOfCubes = nums => nums.reduce((a,b) => a + Math.po ...

What is the reason for the malfunction of this JavaScript code designed for a simple canvas operation?

I'm having trouble with the code below. It's supposed to display a black box on the screen, but for some reason it's not working properly. The page is titled Chatroom so at least that part seems to be correct... <html> <head> &l ...

What is the best way to use jQuery and "Long Polling" to dynamically update HTML pages on an Indy HTTP server?

After thoroughly reviewing the content in the article Simple Long Polling Example with JavaScript and jQuery, I came across a paragraph titled "Long Polling - An Efficient Server-Push Technique," which discusses the Long Polling technique merges the eff ...

Inability to update Vue.js component data even after a successful GET request

I am encountering an issue with a component that initially contains a default object, and then fetches a populated object via a GET request upon creation. Despite successfully updating this.profile within the method, the changes do not seem to propagate ...

Angular is failing to properly display the <br> tags in my JSON data

I am attempting to utilize Angular to display an element from JSON on the page, but it is not working as expected. My goal is simple, yet I am encountering difficulties. Below is the code snippet: http://jsfiddle.net/sqxmyrcj/1/ (function(){ var app ...

Unauthorized Access with Ajax jQuery

While working on an ajax request using Jquery, I encountered a dilemma. Even though the page is only accessible to logged in users, my cookies are not being sent along with the request. This results in a 401 error. I am already logged in, so why aren' ...

The addition of one hour to the date time format increases the total time

Currently, I am retrieving a datetime column value from a database table as 2015-03-04 21:00:00 UTC. When attempting to convert this format into a datetime picker, the following code is used: date = moment($("#event_start").val()); // date time value fro ...

Creating a dynamic group in JSPlumb for Angular and adding nodes to it after the group has been successfully created in Angular 7

I am attempting to create a jsplumb group and then dynamically add nodes to it. However, I have encountered an issue where the documentation states that a node must be created first before being added to the group. In my case, I need to add the group first ...

When collapsing an accordion, Bootstrap radio buttons fail to properly select

I have attempted various methods to achieve the desired functionality of having the accordion content close and open accordingly when checking a radio button, while also having the button visually appear as 'checked'. For a more in-depth example, ...

Having an issue with Vue Router in Vue 2.0, encountering an error

I encountered the following error message: [Vue warn]: Unknown custom element: <router-view> - did you register the component correctly? For recursive components, make sure to provide the "name" option. I double-checked that the Vue router ...

Changing the Style of a CSS Module Using JavaScript

Embarking on a journey into Javascript and React, I am currently working on my first React app. My aim is to adjust the number of "gridTemplateRows" displayed on the screen using a variable that will be updated based on data. Right now, it's hardcode ...

JavaScript throws a "null is null or not an object" error when attempting to

I am dealing with a div that contains flash content in the form of Open Flash Chart. However, I encounter a javascript error when trying to remove child divs using $("#mydiv").children().remove() specifically in IE 8: The error message reads: "null is n ...

I am facing difficulty in getting React to recognize the third-party scripts I have added to the project

I am currently working my way through the React Tutorial and have encountered a stumbling block. Below is the HTML markup I am using: <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=devi ...