Is there a way to retrieve the left offset of a floating element even when it is positioned outside the viewport?

My current situation involves creating several panels that are stacked side by side within a main container. Each panel takes up 100% of the viewport width and height. I want to be able to horizontally scroll to each panel when clicking on their respective link. While this can be achieved with pure CSS, I am now delving into jQuery and would like to use the .scrollTo() method for this purpose.

Previously, when the panels were arranged vertically, I was able to easily obtain the top offset of each panel and scroll to their positions successfully.

However, with the horizontal layout, I am encountering difficulties in obtaining the left offset of the panels. The values I get for the left offset are all zero. In theory, considering a viewport width of 1920px, the left offset of the 2nd panel should be at 1920px, the 3rd at 3840px, and so forth.

After some research, I discovered that the issue may be due to the panels being outside the viewport. To test this theory, I adjusted the width of the panels to 20% so they would remain visible in the viewport, and then attempted to retrieve their left offsets, which proved successful.

To address this problem, I need to understand why this behavior occurs and how to resolve it. Although it may seem like reinventing the wheel, my goal is to learn jQuery thoroughly. Any assistance on this matter would be greatly appreciated :) Below are snippets of my progress thus far.

Thank you.

The Markup:

<div class="mainWrapper">
  <section class="panel" id="panel-1"></section>
  <section class="panel" id="panel-2"></section>
  <section class="panel" id="panel-3"></section>
  <section class="panel" id="panel-4"></section>
</div>

The CSS:

.mainWrapper, .panel {
  position: relative;
  height: 100%;
}

.mainWrapper {
  top: 0;
  left: 0;
}

.panel {
  display: inline-block;
  background: rgba(255, 255, 255, 1);
}

The Javascript:

$(document).ready(function() {
  var $panelWrapper = $('.mainWrapper');
  var $panels = $('.mainWrapper').find('.panel');
  var $panelScrollPos = new Array();

  $panels.each(function(i) {
    //This is where I'm facing issues. It's not working as expected
    $panelScrollPos[i] = Math.round($(this).offset().left - $panelWrapper.offset().left);

    alert('Panels position are: ' + $panelScrollPos[i]);
  });
});

Please note that I have used the .width() method to set the width of .mainWrapper and .panel elements. I haven't included it in the snippet as it is functioning correctly.

Answer №1

In order to ensure that your inline-block elements remain on a single line regardless of the wrapper's width, you can achieve this by resetting the white-space property:

#wrapper {
    white-space: nowrap;
    width: 100%;
}
.child {
    display: inline-block;
    white-space: normal;
    width: 100%;
}

Your fiddle has been updated: http://jsfiddle.net/n3e6xzbj/

Answer №2

For your solution, consider utilizing the getBoundingClientRect method.

Upon calling this function, you will obtain the desired left position information.

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

Guide on Executing a Callback Function Once an Asynchronous For Loop Completes

Is there a way to trigger a callback function in the scan function after the for await loop completes? let personObj = {}; let personArray = []; async function scan() { for await (const person of mapper.scan({valueConstructor: Person})) { ...

The child module invokes a function within the parent module and retrieves a result

Guardian XML <tr [onSumWeights]="sumWeights" > Algorithm sumWeights(): number { return // Calculate total value of all weights } Offspring @Input() onTotalWeights: () => number; canMakeChanges() { return this.onTota ...

a stand-alone Node.js application connecting to a self-signed WebSocket (WSS) server

I am currently working with a node server (Meteor.js) that needs to communicate with another server using websockets. Since the communication is strictly between servers and does not involve direct users, I have decided to use a self-signed certificate. I ...

Utilizing a third-party API within the next/api endpoint

I've recently started working with NEXTJS and developed a weather application. I'm integrating the openweather API, but I'm unsure how to use it within the next/api. I attempted creating a file named today.js inside the next/api directory an ...

Using jQuery to create dynamic elements that fade out with timers

My website has a simple message system that displays messages in a floating div at the top of the page. Each message is supposed to fade out after a certain amount of time, but I want users to be able to pause the fading process by hovering over the messag ...

What might be the reason for the border not reaching the bottom of the popup in my chrome extension?

I am currently working on a Chrome extension and using Bootstrap 5 with Sass to style its popup. However, I have encountered an issue where the border of the popup does not extend to the bottom as expected. What could be causing this problem? popup.html & ...

Utilizing data attributes in E2E testing for optimal results

We have decided to transition from using tag and classname selectors to data attributes in Cypress for our E2E testing. This change is intended to make the selectors more robust and less prone to breaking. Specifically, Cypress recommends using data-cy, d ...

Place the item at the top of the list before scrolling downwards

I'm struggling with what seems like it should be a simple task. My goal is to add new items to the top of a list and have the list scroll down to show the new item. So far, I've managed to create and add a new list item using this code snippet: ...

Unable to set the height of WebDataRocks as a percentage

I've recently started using WebDataRocks and I'm having trouble getting the height to fill the window. Despite what the documentation says (), which states, "The height of the pivot table in pixels or percent (500 by default)". The code snippet ...

Developing a custom mixin to alert a banner at the top of the webpage

I currently have a feature on my website that triggers a pop-up notification whenever a message is received from another user. The pop-up consists of a div displaying the content of the message along with a close button. After exploring various methods to ...

Run the GetServerSideProps function every time the button is clicked

Struggling with my NextJS app development, I encountered an issue while trying to fetch new content from an API upon clicking a button. The server call is successful, but the update only happens when I refresh the page rather than triggering it with the bu ...

What is the best way to extract the JSON data from a client-side GET request response?

Here is my request from the client side to the server in order to retrieve JSON data. fetch("/" + "?foo=bar", { method: "GET", }).then(response => { console.log(" ...

What is the best way to evaluate two values using jQuery?

I need to select them and add a new class. <div class="count_1"> <span class="percentage">10 %</span> </div> <div class="count_2"> <span class="percentage">90 %</span> </div> if (parseInt($(".count_1.per ...

Create a customized HTML popup featuring various packages

I am struggling to create an HTML popup within a React component due to some errors Here is the code snippet: <div> <button class="toggle">Button</button> <div id="link-box"> <ul> ...

Passing multiple functions to child components in ReactJS as a single prop

I am utilizing the technique of passing multiple functions as individual props from the parent component to its child components. Everything is working correctly without any errors or problems, but I'm interested in exploring if there is a more effici ...

Determine the initial left position of a div element in CSS prior to applying

Scenario : const display = document.querySelector('.display'); const container = document.querySelector('.outer-div'); document.addEventListener("click", (event) => { if (!event.target.closest("button")) return; if(event ...

What causes a webpage to overflow when using the position:absolute property?

Despite my understanding that an element positioned absolutely should be removed from the normal content flow, why does it still cause the page to overflow? Running the code snippet below reveals a horizontal scrollbar, which I didn't expect. .rela ...

The nodejs express application encountered a CSRF token mismatch when attempting to make an ajax post request

Software Stack: Node.js, MongoDB, Handlebars, Bootstrap In controllers/products/index.js module.exports = function (router) { router.post('/add',function(req,res){ // implementation logic }); }; On the website, users can add pr ...

Cross-Origin Resource Sharing (CORS): The preflight request response does not satisfy the access control check

I've been facing an issue with a simple POST method to my API through the browser. The request fails, but when I try the same on Postman, it works fine. The response includes a JSON string and two cookies. In an attempt to resolve this, I set the hea ...

What is the maximum number of JSON responses that can be handled by AJAX?

Upon entering the site, I am attempting to receive a JSON as an AJAX response. However, I am curious if there is a limit to the size of the object I can retrieve - whether through a GET or POST request? $http({ method: 'POST', url: &apos ...