JS: Ensure to scroll down once the div element has been "unhidden"

Within a div element, I have an abundance of content:

<div id="x" class="unhidden">
    text and additional divs
</div>

The CSS class 'unhidden' is defined as:

display: block;

Upon clicking a link, the element with the id='x' changes to class='hidden' through javascript. The 'hidden' class includes:

display: none; 

Subsequently, the div element becomes hidden. Everything seems to be working fine so far. Now, my objective is to revert and reveal the full div='x', while also scrolling down to a specific section within the id='x' div.

Hence, when the back button is clicked, first, the class reverts back to unhidden using javascript. Then, within the same function, this script is executed:

window.scroll(0, findPos(document.getElementById(GoTo)));

'GoTo' represents the ID of the particular div that needs to be scrolled to. Utilizing this function for scrolling:

function findPos(obj) {
    var curtop = 0;
    if (obj.offsetParent) {
       do {
            curtop += obj.offsetTop;
       } while (obj = obj.offsetParent);
      
       return [curtop];
   }
}

The scripting correctly determines the position to navigate to, but it fails to execute the scroll.

The scrolling process works smoothly when isolated from the hiding/showing functionality. However, in this scenario, there appears to be a blockage caused by the toggle between hidden and unhidden states.

Do you have any potential solutions or insights to offer?

Answer №1

It appears that the browser processes all of your JS code before returning control to the rendering engine. This means that changing the class may not actually render the element visible again at the moment when your code calculates the element position, as hidden elements do not have a defined position.

To address this issue, try wrapping your entire window.scroll call in an anonymous function and adding a slight delay using setTimeout:

referenceToDivElement.className = "unhidden";
var targetElement = document.getElementById(GoTo);
window.setTimeout(function() {
  window.scroll(0, findPos(targetElement));
}, 5);

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

Extract each line of text from the ul li tags at every level of the hierarchy with the help of

I am looking to extract a list of strings from the ul and li elements with slash (/) separating each level up to the nth level using JavaScript. I attempted to use both the Jquery.map and each functions, but unfortunately, I was unsuccessful. ...

Using jQuery to hide an element when the script is invoked

I'm encountering an issue where I create a file containing HTML and JavaScript that is loaded later via AJAX. One of the files should hide an element after it is loaded, but for some reason, it is not working. I have tried various methods to hide the ...

Styling Material UI height in select elements (React)

Currently, I am developing a react application that utilizes Material Dashboard. I am encountering an issue with the height of a Select (drop-down list) component. See image here On the right side of my app, there is a standard input field and I would li ...

Exploring Material-UI: Leveraging makeStyles and CSS-In-JS for customizing library component styles

I'm currently utilizing Material-UI to construct a form using makeStyles and CSS-In-JS for styling purposes. I have a form component from the Material-UI library that I want to style according to my needs. My main focus is on how to address classes or ...

What steps can I take to ensure that the children of my dropdown menu do not trigger the focusout event of the dropdown itself?

It's frustrating how children inherit their parent's event listeners by default, even if they are added after the listener was created. This just seems counterintuitive to me. I only want to add a listener to the parent element, not to all of its ...

Learn how to utilize Javascript to easily drag and drop an image within the same block

I am encountering an issue with dragging and dropping images or swapping them using JavaScript. I have tried to implement this in the code below, where clicking on icons moves them onto a colored div. However, I am now trying to drag and drop the images wi ...

What is the best way to switch back and forth between two div elements?

I've been attempting to switch between displaying div .cam1 and div .cam2, however, I can't seem to get it to work. Here's the code snippet in question: HTML: <div class="cam1"></div> <div class="cam2"></div> CS ...

CodePen experiencing issues with JS/jQuery coding functionality

Experimenting on CodePen, I am practicing using JS and jQuery with HTML. HTML: <button>asdasads</button> JS: $('button').on('click', function() { alert('woot'); }); Visit this pen, unfortunately it's ...

Communicate through PHP and JavaScript chat to display HTML content in the chat window

I have been attempting to display HTML output in the chat window but instead, it is showing the HTML code. Here are the two files involved in the chat system: chat.js `function chatHeartbeat(){ var itemsfound = 0; if (windowFocus == false) { var ...

Increasing the size of the td element when including a new row

Here is an html page example that I am working with: However, when I add a new row beneath the existing row that contains a div block and form within it, I notice that the td tag in the first row expands in width, as depicted in the image below. Below is ...

Navigating a Frame and Clicking a Link with Puppeteer: A Step-by-Step Guide

I am facing an issue with clicking on an anchor link within a page that is supposed to open a new tab for exporting a PDF. The problem arises because this link is located inside a frame within a frameset structure as shown below: https://i.stack.imgur.com ...

Angular, choose, establish a default option

Despite my attempts, I am struggling to set the default option for a select element using AngularJS. My Technologies: AngularJS, Angular-UI-router, Bootstrap Key HTML snippet: <select ng-model="selectedCompany" ng-options="c.name for c in companies" ...

The ul media queries have malfunctioned

In the .gallery section, there are 12 li elements that contain images. Originally, I used media queries to adjust the number of columns in the grid to 6, 4, 3, and 2 based on the browser width. However, when I tried to create a size ratio of 2:1 for all ...

The div background image in Vue.js is displaying a 404 not found error

I've encountered an issue while trying to set a background for a div. Strangely, when using the same relative path with an img tag everything works fine, but as soon as I try to achieve the same result with a div, I receive a 404 error. This img tag ...

"Enhance user experience with Sweetalert 2's customizable sorting options for select inputs

Here is the code snippet that I am currently working with: this.getdata((params.....).then((data) => { var selectOptions = []; for (let i = 0; i < data.length; i++) { selectOptions[data[i].id_calc] = data[i].surname + " " + data[i ...

How do I go about adding a specific class to every row within a Vue.js table?

I have an html table structured like this : <tbody> <tr v-for="employee in employees" :key="employee.EmployeeId" @dblclick="rowOnDblClick(emplo ...

Ajax is malfunctioning and failing to fulfill my needs

I cannot get Ajax to submit no matter what. I've been struggling for hours... script: <script> $(document).ready( $("#submit").click(function(e) { e.preventDefault(); $.ajax({ url: "https://maps.googleapis.com/maps/ ...

Exposed object accessible from the jQuery plugin

My experience with two jQuery plugins has been quite interesting. The first one: ;(function($){ function CbUploader(element,options){ widget=this; ..... } $.fn.cbUploader = function(options){ new CbUploader(this,option ...

Ways to show error at the top of the page rather than next to the input HTML element

Is there a way to show errors at the top of the page instead of next to the input HTML element? Please provide suggestions. <ng-form name="frmdisbursementScheduleMaintenance"> <div style="padding-bottom: 8px;"> &l ...

I'm looking to input user data into a table using a unique ID, but the console is alerting me with a "Warning: Each child in a list should have a unique 'key' prop." notification

Here's my custom Add User React component: import axios from "axios"; import { useState } from "react"; const CustomAddUserComponent: React.FC<{ fetchUserData: () => void }> = ({ fetchUserData, }) => { const [name, setName] = useState ...