Transferring the offset of jQuery from one element to another results in their positions being misaligned

In the quest for aligning content vertically between two divs, I have encountered a challenge. Despite my efforts to adjust offsets and heights, the new element in the second div still does not align perfectly with the first one. This is evident in the code snippet provided below.

The discrepancy lies in understanding why there is a difference between tag_offset.top and test_tip.offset().top, even though they are explicitly set to be equal during the instantiation of test_tip.

var tag_offset = $('.jt-tooltip-tag').offset();
tag_offset['left'] = 0;
var tag_text = $('.jt-tooltip-text').text();

var test_tip = $('<div class="jt-sidebar-tip">').text(tag_text).offset(tag_offset).appendTo('#jt-tooltip-sidebar');
.middlebar {
  width: 49%;
  float: left;
}

.sidebar {
  height: 500px;
  width: 49%;
  float: right;
  border: 1px solid purple;
}

.jt-tooltip-tag {
  font-weight: bold;
  background-color: #14c9c9;
}

.jt-tooltip-text {
  display: none;
}

.jt-sidebar-tip {
  position: relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="page">
  <h1 class="header">
    Omigosh a header!
  </h1>
  <div class="content">
    <div class="middlebar">
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin nec tortor justo. Donec magna neque, interdum eu diam ut, efficitur pharetra ligula. Aenean libero justo, feugiat a est a, hendrerit cursus justo. Donec vehicula ligula ut diam bibendum, vel
      convallis purus blandit. Nulla <span class="jt-tooltip"><span class="jt-tooltip-tag">facilisi.</span><span class="jt-tooltip-text">This should be vertically-aligned with facilisi.</span></span> Donec pretium, leo at commodo dignissim, eros
      ligula vulputate sem, quis iaculis turpis est ac erat. Ut ultrices mauris efficitur tellus gravida convallis vitae ac magna. Nullam vel enim ut eros tempor dictum et quis risus. Aliquam finibus sed justo eu porttitor.
    </div>
    <div class="sidebar" id="jt-tooltip-sidebar">
    </div>
  </div>
</div>

Answer №1

To position an element relative to the document, you must apply the CSS style position: absolute;. Additionally, you need to adjust the left offset to place it within its container. I achieved this by setting it to

$("#jt-tooltip-sidebar").offset().left
.

var tag_offset = $('.jt-tooltip-tag').offset();
tag_offset.left = $("#jt-tooltip-sidebar").offset().left;
var tag_text = $('.jt-tooltip-text').text();

var test_tip = $('<div class="jt-sidebar-tip">').text(tag_text).offset(tag_offset).appendTo('#jt-tooltip-sidebar');
.middlebar {
  width: 49%;
  float: left;
}

.sidebar {
  height: 500px;
  width: 49%;
  float: right;
  border: 1px solid purple;
}

.jt-tooltip-tag {
  font-weight: bold;
  background-color: #14c9c9;
}

.jt-tooltip-text {
  display: none;
}

.jt-sidebar-tip {
  position: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="page">
  <h1 class="header">
    Wow, a header!
  </h1>
  <div class="content">
    <div class="middlebar">
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin nec tortor justo. Donec magna neque, interdum eu diam ut, efficitur pharetra ligula. Aenean libero justo, feugiat a est a, hendrerit cursus justo. Donec vehicula ligula ut diam bibendum, vel
      convallis purus blandit. Nulla <span class="jt-tooltip"><span class="jt-tooltip-tag">facilisi.</span><span class="jt-tooltip-text">This should be vertically-aligned with facilisi.</span></span> Donec pretium, leo at commodo dignissim, eros
      ligula vulputate sem, quis iaculis turpis est ac erat. Ut ultrices mauris efficitur tellus gravida convallis vitae ac magna. Nullam vel enim ut eros tempor dictum et quis risus. Aliquam finibus sed justo eu porttitor.
    </div>
    <div class="sidebar" id="jt-tooltip-sidebar">
    </div>
  </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

What is the reasoning behind having two separate permission dialog boxes for accessing the webcam and microphone in flash?

I am currently using a JavaScript plugin known as cameratag () in order to record videos through the web browser. This plugin utilizes a flash-based solution. When the flash application requests permission to access the webcam, it presents a security dialo ...

Is there a way to assign a texture to only one side of a plane while having a color on the opposite side?

I'm currently experimenting with creating a plane in three.js where one side is a texture and the other side is a solid color. My initial attempt looked like this: var material = new THREE.MeshBasicMaterial({color: 0xff0000, side: THREE.FrontSide, ma ...

Ways to retrieve the previously selected option in a dropdown list

I am working with a form that includes a dropdown list featuring options such as apple, gova, lemon, and more. Each option has an associated counter - for example, apple=5, gova=3, lemon=6. If I initially select apple from the dropdown, the count for apple ...

What could be causing Express to display a different page than the one specified in res.render?

Upon trying to view the compare.ejs page, I encountered an unexpected issue where a different page was being rendered instead. What could be causing this discrepancy? Here is my app.js code: var compare = require('./routes/compare')(nav); app.u ...

Breaking down arrays in Typescript

Let's say I have an array like this: public taskListCustom: any=[ {title: 'Task 1', status: 'done'}, {title: 'Task 2', status: 'done'}, {title: 'Task 3', status: 'done'}, {title: 'Task ...

Can the AngularJS icon adapt to different lists?

I'm currently developing in AngularJS / Jade and I need to implement functionality where an icon changes when a user clicks on something. The code I have right now looks like this: a(onclick='return false', href='#general', data-t ...

What is the most efficient way to populate a dynamic table in a form with a user's past responses using PHP?

Explaining my thought process through a complex title might be challenging, but let me provide an example to clarify: Imagine I am requesting the user's favorite Rock albums, including albumName and albumArtist. Initially, there is a table with one r ...

The dropdown Select2, filled from JSP/Ajax, loses functionality after initial use with a button

In my webpage, there are 12 filters that query a database using select2 dropdowns. Upon page load, the selects are automatically populated with data from a java controller. Here's an example snippet from a JSP page: <select id="selectFPA" name=" ...

JavaScript Arrays with Four Dimensions

Looking for a solution to generate arrays with any number of dimensions, including 4D arrays. I'm interested in being able to use the function to create an array and then access it like this: arr[3][2][23][12] = "amazing"; ...

Having trouble with request-promise in node.js? It's not functioning as anticipated

Currently utilizing the request-promise node module. Following the documentation closely to ensure correct setup, however encountering the following error: Unhandled rejection StatusCodeError: 400 - "{\n \"error\" : {\n \"s ...

jQuery event handler for changing and blurring elements

Imagine a situation where you only want an event to be triggered when you exit an input field. This is because the event initiates a type of request, like an ajax postback, that updates the input fields. If a change event were used, it could create an infi ...

"Tailwind - where your brand shines with a sleek, modern logo that stands

I have a specific title width that I need to adhere to, and I'm looking to place a logo after the last word in the title. When the title is too lengthy, it wraps onto a second line. For example: My Title (insert logo here) Check out this CodePen us ...

I am having trouble getting my CSS styles to apply to nested components within Bootstrap React components

Currently I am learning react and in the process of creating a website using react-bootstrap. While working on my navbar, I encountered an issue where I was unable to change the font and font-color of the navbar items. The CSS that I applied only affected ...

Troubleshooting: Vue JS failing to recognize new objects and properties in HTML

Within my Vue instance, I have a method named `loadPlannedAlerts` that performs an AJAX call to retrieve JSON data. This method is called during the `mounted` lifecycle hook of my Vue JS instance. The retrieved JSON object consists of key-value pairs struc ...

Obtain the HTML content of a webpage a few seconds following its initial loading

Currently, I am working on a script in nodejs to automate the process of fetching data from an online directory. Although this is new territory for me, I decided to go with javascript as it is a language I am comfortable with. After some research on Googl ...

Using jQuery to search for corresponding JSON keys in the PokéAPI

Currently, in my development of an app, I am searching for and implementing an English translation of a language JSON endpoint using the PokéAPI. The challenge lies in identifying the correct location of the English language key within the array response, ...

Using Javascript math to create a backdrop effect by drawing rectangles around multiple other rectangles

Important Note: In this discussion, the term overlay will be used interchangeably with backdrop. Currently, I am developing a guide mode where I emphasize certain elements by making them stand out against a darker semi-transparent background. The approac ...

What is the method to link a progress bar to the value of a text input?

I'm currently working on an application where users need to input the percentage of their skill proficiency, and I want the progress bar to automatically reflect that value. I require assistance with this task, preferably using PHP only, but Java can ...

"Incorporating images into a dropdown menu by utilizing the option value attribute

After attempting various solutions without success, I am reaching out for help as I am unable to find a fitting solution for my problem. The issue at hand is adding images to select list options based on the option value, with the limitation of not being a ...

Straightforward, rudimentary example of Typescript knockout

I am hoping to successfully implement a basic TypeScript Knockout example. I utilized Nugget to acquire the TypeScript Knockout and downloaded Knockout 3.0.o js. Below is my TypeScript file: declare var ko; class AppViewModel { firstName = ko.observa ...