`Monitoring and adjusting page view during window resizing in a dynamic website`

Situation:
Imagine we are reading content on a responsive page and decide to resize the browser window. As the window narrows, the content above extends down, making the entire page longer. This results in whatever content we were previously viewing being pushed further down the page as we continue to adjust the window size.

Example:
For example, let's say we were exploring the Helper classes section on this webpage. When we shrink or expand the window significantly, the section we were focused on moves up or down within our current view.

Prompt:
Is there a solution to this issue? Can we maintain our current view of the page regardless of changes to the content above when resizing the window?

Thoughts:
One suggestion is to use JavaScript to detect window resize events and automatically scroll the page to the topmost element that was visible before the resize. However, concerns arise about potential performance impacts, especially on larger pages. Additionally, determining the exact "top-most element" may be challenging, as overlapping elements can complicate this definition.

This seems more like a flaw in default browser scrolling behavior rather than an inherent problem with responsive design. It raises questions about whether the current behavior aligns with user expectations or if improvements are needed for a smoother browsing experience.


Edit 4

A revised demo has been created based on Rick Hitchcock's suggested solution.

Using jQuery:

//onresize:
var scrollAmount;

if (topNode.getBoundingClientRect().top >= 0) {
    scrollAmount = $(topNode).offset().top - topNode.getBoundingClientRect().top;
} else {
    scrollAmount = $(topNode.offset().bottom - topNode.getBoundingClientRect().bottom;
}
$(window).scrollTop(scrollAmount);

The demo may behave inconsistently across browsers, so I have also hosted it here. Additional fixes are required for IE, Opera, and Safari related to elementFromPoint.


Edit 3

Appreciation for your assistance, Rick Hitchcock. Your insights have been invaluable. As discussions veer towards cross-browser compatibility challenges, I've accepted your answer as it addresses the core question. Nonetheless, refinements are still needed regarding cross-browser considerations, topNode selection criteria, and handling cutoff elements.

An interesting scenario arises:

Upon further exploration, transitioning from a small viewport to a larger one can lead to unexpected behavior at the bottom of the page. If additional elements become visible due to the wider viewport, locking the topNode may not always work as intended. Resolving this anomaly requires careful consideration and testing, particularly concerning how Opera handles such scenarios.

These edge cases will be addressed systematically, starting with evaluating the impact of scroll bottoms and devising measures to ensure consistent behavior across different browsers.

Answer №1

Below is my latest creation:

(function(){
   var topNode;

   window.onscroll=function() {
     var timer;
     (function(){
        clearTimeout(timer);
        timer= setTimeout(
                 function() {
                   var testNode;
                   topNode= null;
                   for(var x = 0 ; x < document.body.offsetWidth ; x++) {
                     testNode= document.elementFromPoint(x,2);
                     if(!topNode || testNode.offsetTop>topNode.offsetTop) {
                       topNode = testNode;
                     }
                   }
                 },
                 100
               )
      }
     )();
   }

   window.onresize=function() {
     var timer;
     (function(){
        clearTimeout(timer);
        if(topNode) {
          timer= setTimeout(function(){topNode.scrollIntoView(true)},10);
        }
      }
     )();
   }
 }
)();

If there were a window.onbeforeresize() function, this would be more straightforward.

Please note that the script does not consider the scrolled position of the element's textNode. Handling this would require only resizing the height of the window. Resizing the width generally causes reformatting.

This code snippet has been tested and works seamlessly on Chrome, Firefox, IE, and Safari.

Edit

How it operates

The use of closures in the code keeps variables private, while timers prevent continuous execution during scrolling/resizing. To enhance understanding, here's another version that simplifies the code structure. It's worth mentioning that the timer within onscroll is necessary in IE due to an issue described here.

var topNode;

window.onscroll=function() {
  setTimeout(
    function() {
      var testNode;
      topNode= null;
      for(var x = 0 ; x < document.body.offsetWidth ; x++) {
        testNode= document.elementFromPoint(x,2);
        if(!topNode || testNode.offsetTop>topNode.offsetTop) {
          topNode = testNode;
        }
      }
    },
    100
  )
}

window.onresize=function() {
  if(topNode) {
    topNode.scrollIntoView(true)
  }
}

topNode tracks the element at the top of the screen as it scrolls.

The function scans from left to right along the 3rd row: document.elementFromPoint(x,2)*

It avoids scanning the 1st row because in IE, when scrollIntoView is used, the element shifts down slightly, making the previous element the new top-most one. This was discovered through trial and error.

Upon window resize, topNode is positioned at the top of the screen.

[*Initially, onscroll scanned left to right along the 11th row (in pixels) until finding an element with just one child. This child was often a textNode but not always. For example:

<div><ul><li>...<li>...<li>...</ul></div>

The div only had one child – the ul. If the scroll position was at the 50th li, scanning left to right incorrectly returned the div because of padding on lis.

The original code has since been updated. ]

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

AngularJS Vimeo API Request Error: "401 Authorization Required"

I've been experimenting with making external API calls to Vimeo from my AngularJS code using $http.jsonp. However, I keep receiving a 401 Authorization required error even though I have included my authorization key in the header. I encountered a simi ...

"Enhance your Angular experience with SweetAlert integration using directives and translation

Currently, I am utilizing the Angular implementation of the SweetAlert plugin from GitHub. I am attempting to pass an Angular directive with translation to the title. The variable being passed as the title is: {{ 'register.confirmation_modal.SUPERI ...

What could be the reason my black overlay doesn't show up when the button is clicked?

Attempting to craft a pop-up window on my own, I encountered an issue. Upon pressing the button, instead of the anticipated pop-up appearing and darkening the background below it, the entire page freezes with no sign of the pop-up box. If I eliminate the ...

Organizing and managing one-on-one table tennis matches using a customized data structure. Leveraging the power of Vue, JavaScript, and

Seeking advice on the best approach for storing table tennis match data in a web application. I currently have a method in place that works, but I'm open to suggestions for improvement. Here is my current idea: matches: [ { id: 1 datePlayed ...

What is the designated color for highlighting an option in Next.js?

This is my first time working on a Next.js project and I see an unfamiliar option. Which selection should I choose? I plan to use JavaScript for the Next.js project, not TypeScript. Just need to figure out which option is currently selected so I can pro ...

Steps for Building and Exporting a Next.js Project Without Minification and Optimization

Is there a way to build and export a Next.js project without minifying and optimizing the output files? ...

Firebase will automatically log users out after one hour of inactivity

After conducting thorough research, I have learned that Firebase updates a refresh token every hour because Firebase ID tokens expire after one hour. It is mentioned that the automatic refreshing of tokens by Firebase occurs without any action required fro ...

Issue with AJAX Complete event not functioning

Currently, I am facing an issue with firing the .ajaxComplete function on a demo site. I have referred to this function from this link. Below is my code : <SCRIPT type="text/javascript"> <!-- /* Credits: Bit Repository Source: http://www.bit ...

Dealing with lag problems while feeding a massive dataset into the Autocomplete component of Material-UI

In my React project, I have integrated the Autocomplete component from Material-UI to enhance user experience. However, when attempting to pass a large dataset of 10,000 items to the Autocomplete component as a prop, there is a noticeable delay of approxim ...

What is the method for inserting data into an array of objects in JavaScript?

I have a question regarding how to push/replace data into an object of an array of objects. Please excuse any mistakes in my grammar. Here is my dummy data: const dummyData = { id: 1, daerah: "Bandung", date:"1668790800000& ...

Change every occurrence of span class red to be a strike tag

I'm attempting to replace all span tags with the red class and their content with a strike tag. However, I've encountered an issue where it doesn't seem to be replacing the specific span tags as expected. Below is the code snippet: let s ...

In React conditional return, it is anticipated that there will be a property assignment

What is the optimal way to organize a conditional block that relies on the loggedIn status? I am encountering an issue with a Parsing error and unexpected token. Can someone help me identify what mistake I am making and suggest a more efficient approach? ...

How to incorporate both image and text links within an HTML div container using JavaScript

I am trying to create a clickable image and text within a div named "films" that both link to the same webpage. However, I am experiencing an issue where only the text link works and the image link is disabled. If I remove the text link, then the image l ...

What is the syntax for implementing the 'slice' function in React?

While working on my React app, I encountered an issue when trying to extract the first 5 characters from a string using slice. The error message displayed was: TypeError: Cannot read property 'slice' of undefined I am utilizing a functional compo ...

How to modify a variable in the Config.json using a Discord.js command

Lately, I enhanced my bot's functionality by allowing it to retrieve the color for embeds from a file specified in my config.json. All I need to do is modify something like: "embedcolor": "00A950" to "embedcolor": "0 ...

What is preventing the addition of links to the navigation bar when using a sticky navigation bar?

Currently, I am in the process of developing a blog website using Django. One of the features I have successfully implemented is a sticky navigation bar. However, I am facing a challenge with adding links to the menu on the navigation bar due to existing ...

Ascending and descending functions compared to Ext.getCmp()

I'm feeling a bit lost trying to figure out which method to use when using grep object - should I go with up(), down(), or Ext.getCmp(ID)? Personally, I find it simpler to assign an ID to the object and then retrieve it using Ext.getCmp('ID&apos ...

Is anyone else experiencing issues with the jQuery slide-in not working on a particular website? How can I determine which version of jQuery is compatible with this site?

Essentially, I am looking to have a div box slide in on the page as it loads. This method has worked successfully on other websites and HTML previews that I have tested it on so far. However, for some reason, it does not seem to work on this specific websi ...

Clarification: Javascript to Toggle Visibility of Divs

There was a similar question that partially solved my issue, but I'm wondering if using class or id NAMES instead of ul li - such as .menu, #menu, etc. would work in this scenario. CSS: div { display:none; background:red; width:200px; height:200px; } ...

Error encountered in jQuery's addClass and removeClass functions: Unable to read the property 'length' of an undefined value

Upon loading my page, I aim to have some of the div elements hidden initially and display only one. Here is a script that accomplishes this goal: <script> $(document).ready(function () { $(".total").click(function () { $("#pi ...