Aligning an element perfectly at the top within a column

I have two columns side by side. The column on the left contains HTML that I cannot control. On the right side, I need to display a comment box that should align with the text clicked on the left hand side.

Is it possible to position an element absolutely in relation to a non-sibling?

Example: https://jsfiddle.net/ark51cLu/4/

<div class="container">
    <div class="left">
      <div class="box1">
        <div class="inner-html-box">
          <p onclick="clicked(event)">Item 1</p>
          <p onclick="clicked(event)">Item 2</p>
        </div>
      </div>
    </div>
    <div class="right">
      <div id="comment-box" class="box2">Item 1 comments</div>
    </div>
</div>

Answer №1

If you want it to look like this,

simply include px in the top value, like so:

box2.style.top = top + "px";

function clicked(ev) {
    var top = ev.target.getBoundingClientRect().top;
    var box2 = document.querySelector('.box2');
    box2.style.top = top + "px";
    box2.innerText = ev.target.innerText;
    console.log(top);
}
.left{
  float: left;
  width:75%;
}

.right {
  float: right;
  width:25%;
}

.box1{
  border: 1px solid red;
}

.box2{
  border: 1px solid blue;
  position: absolute;
  top: 0;
  right: 0;
}
<div>
<div class="left">
  <div class="box1">
  <p onclick="clicked(event)">Blah 1</p>
      <p onclick="clicked(event)">Blah 2</p>
  </div>
  </div>
<div class="right">
<div class="box2">Blah 1 stuff</div>
  </div>
</div>

Answer №3

Since this is not tagged with jQuery, here's a vanilla JavaScript version.

const box1 = document.querySelector('.box1')
const box2 = document.querySelector('.box2')

box1.addEventListener('click', (e) => {
  let top;
  if(e.target.nodeName = "P") {
    top = e.target.getBoundingClientRect().top
    box2.style.transform = `translateY(${top}px)`
  } else {
    return
  }
})
.left{
  float: left;
  width:75%;

}

.right {
  float: right;
  width:25%;
  overflow: hidden
}

.box1{
  border: 1px solid red;
}

.box2{
  border: 1px solid blue;
  position: absolute;
  top: 0;
  right: 0;
  transition: transform .3s
}
<div>
  <div class="left">
    <div class="box1">
      <p>Blah 1</p>
      <p>Blah 2</p>
    </div>
  </div>
  <div class="right">
    <div class="box2">Blah 1 stuff</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

Dynamically extract key values from JSON data and display them on an HTML page with checkboxes for selection. Generate a new JSON object containing

I am facing the challenge of parsing an unknown JSON with uncertain key-value pairs. As I do not have prior knowledge of the keys to access, my goal is to traverse through every key in the JSON and display all keys and their corresponding values on the scr ...

Arranging data in Ember: sorting an array based on several properties in different directions

Is it possible to sort a collection of Ember Models by multiple properties, where each property can be sorted in different directions? For example, sorting by property a in ascending order and by property b in descending order? Update I attempted to use ...

Is my implementation of Model and Views in backbone.js accurate?

I'm new to backbone.js and I've just created my first page. I'm curious to know if I'm headed in the right direction with my approach (if there even is a "correct" way in software development). Is there a way to automatically bind mode ...

Maintaining the position of the screen as you type in information that is located outside of the container

I am encountering an issue with the input/text-area element in absolute position extending halfway outside the container. The screen position seems to follow the caret as I type, but I'd prefer to keep writing and have part of the text hidden beyond t ...

Accessing a nested value in MongoDB: A step-by-step guide

I am working on a document where I have a category object containing fields for category name, cost, and date. My task is to retrieve categories specifically from the year "2022". The console is currently showing "[]" output, but I want it to display categ ...

Is there a way to specifically call the last promise in a loop?

I'm new to promises and could use some help. I have a situation where promises are resolving randomly, how can I ensure that the last promise in the loop is resolved after the full loop executes? For example, if this.selectedValues has 4 values, som ...

CakePHP does not recognize the input type "number" in forms

My goal is to create a form field that only accepts numbers as input. However, when I attempt the following code in CakePHP: <?php echo $this->Form->input('aht',array( 'label' => 'AHT', 'type' = ...

Struggling to generate a cookie through an express middleware

I'm currently working on setting up a cookie for new user registrations in my app to track their first login attempt. I came across this thread which provided some guidance but I'm still facing issues. Below is the snippet of my code: // Middle ...

What is the best way to divide a list in a Django template?

Currently, I am working on pagination in Django and looking to display the page numbers that come after the current page. The code snippet I am using is as follows: {% for page in blogs_page.paginator.page_range|slice:"0:{{ blogs_page.number }}" %} Howev ...

Protecting Node.js Files

As I prepare to embark on creating a new website, my main goal is to collect form input values such as dropdowns and radio boxes from the client without requiring user accounts. These values will be used for sensitive calculations, making security a top pr ...

How to use Vue v-bind to fetch an array object from a different array iteration

I am currently working on a project where I have developed a table component that is utilized across multiple pages with different configurations. Each table has its own configuration stored in a separate file, containing keys, titles, and size classes for ...

What is the best way to extract specific values from one JSON object and transfer them to another using lodash?

//I have a pair of objects var obj1={ "name":"mayur", "age":23 } var obj2={ "name":"keyur", "age":29, "limit":54, "surname":"godhani" } //I am familiar with one approach var j1 = {name: 'Varun', age: 24}; var j2 = {code: &ap ...

The Express.js application functions properly on a local environment, but encounters issues when deployed on Heroku

Currently, I am experiencing an issue with deploying a music visualizer that I created. It seems to work perfectly in all scenarios except when I click on a song to play from the search bar, where I keep encountering a '503 (Service Unavailable)' ...

How to position a static element using CSS

I'm trying to align an image in the center of the screen, but I've run into some trouble. Typically, this is easy by setting the width of a div and using margin: auto;. However, I also need the div to have the position: fixed; property, which see ...

Increasing the contents of a JavaScript array within a conditional statement

I find myself in a predicament where I need to dynamically add elements to a multidimensional array depending on a specific condition. This means that the type of element to be added will vary based on the condition. if(type == 'text-box'){ ...

Reliable Dropdown Navigation Bars

Once I have successfully implemented three dynamic drop down menus using the combination of jQuery, AJAX, and PHP, the next challenge arises. After populating the dropdown menus based on user selections (e.g., selecting a value in the first dropdown menu ...

Tips for creating Card-Title responsiveness across various screen dimensions with Bootstrap 4

I'm a beginner in web design and I'm wondering if it's possible to adjust the font-size of the card-title and the size of the card image based on different screen sizes using bootstrap 4. When viewed on small screens, they appear too large. ...

Extracting a parameter from a URL using C#

Imagine having a URL such as http://google.com/index.php?first=asd&second=mnb&third=lkj What is the method to extract the second value (mnb) using C#? ...

Console log displays varied outputs for identical arrays

Having an array in a static form and one that is filled using the ajax post function, I initially planned to replace the static array with the dynamic one. However, upon closer inspection, it seems that the two arrays are not matching. Array 1 (static) ...

Revive the design of a website

As I work on creating my own homepage, I came across someone else's page that I really liked. I decided to download the page source and open it locally in my browser. However, I noticed that while the contents were all there, the style (frames, positi ...