O
O
oelena2020-05-13 12:01:56
JavaScript
oelena, 2020-05-13 12:01:56

How to change the position of an element relative to hovering over other elements?

https://jsfiddle.net/ElenaOr/Luchx79s/1/ - I can't figure out how to correctly write in pure js so that a large element is positioned under small elements at the moment when we hover over a small element with the cursor.

var location = targetX.getBoundingClientRect(); - this element shows the position of a small square (looked in the console). But how to calculate the position of a large relative to it, I can’t figure it out.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
MagicMight, 2020-05-13
@oelena

D
drawnofmymind, 2020-05-13
@drawnofmymind

var colorsBig = document.querySelector('.big-color');
var colorsElements = document.querySelectorAll('ul li');

for(var colorElement of colorsElements) {
  colorElement.onmouseenter = function(event) {
    colorsBig.classList.remove('hidden');
    var targetX = event.target;
    var location = targetX.getBoundingClientRect().x;
    colorsBig.style.left = location + 'px'
  }
  colorElement.onmouseleave = function() {
    colorsBig.classList.add('hidden');
  }
}

(positioned relative to the x-axis)
getBoundingClientRect() - Returns a property object

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question