Alexandr Belov
Alexandr Belov

Reputation: 1834

Javascript / Positioning an element according to another element's position

I want my div (with style="display: none; position: absolute" by default, it's only visible when a cell is clicked) to appear in 30px left from the clicked cell in a table. addevent stands for my div which I want to put 30px left from the cell. So, I want my div to appear 30px left from the clicked cell's left. What am I doing wrong?

var cell = document.getElementsByTagName('td');
for (var i=0; i<cell.length; i++) {

cell[i].onclick = function() {

var data = this.getAttribute('data-cell');
editEvent = document.getElementById('addevent');
editEvent.style.cssText ='display: block;';
this.style.position = 'relative';

var rect = this.getBoundingClientRect();
editEvent.style.left = rect.left + 30;
editEvent.getElementsByTagName('input')[3].value = data;
};

Upvotes: 4

Views: 1229

Answers (1)

Ciro Costa
Ciro Costa

Reputation: 2585

As i've stated in comments, it might be an error of unity. See the example:

var $floating = document.querySelector('.floating-div');
var $contentDivs = document.querySelectorAll('.content-div');

for (var i = $contentDivs.length; i--;) {
  $contentDivs[i].addEventListener('click', function () {
    var rect = this.getBoundingClientRect();

    $floating.style.top = rect.top - 30 + 'px';
    $floating.style.left = rect.left - 30 + 'px';
    $floating.classList.add('show');
  });
}
.content-div {
  border: solid 1px black;
  position: relative;
  width: 120px;
  top: 120px;
  left: 120px;
  float: left;
}

.floating-div {
  border: solid 1px red;
  opacity: 0;
  position: absolute;
  top: 0;
  left: 0;

  transition: opacity .2s ease, left .1s ease;
}

.floating-div.show {
  opacity: 1;
}
<div class="floating-div">
  <p>i'll float!</p>
</div>

<div class="content-div">
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iusto rerum aspernatur dolores, eos laborum illo, placeat minima, dolorum eaque perferendis ut nam eligendi quas quod minus deleniti dicta aut nemo.</p>
</div>

<div class="content-div">
  <p>I'm juust another content-div! Hey hey hey</p>
</div>

Upvotes: 1

Related Questions