Search code examples
javascriptgetboundingclientrect

Top and Left Coordinates Not Working On getBoundingClientRect() - Javascript


I have a menu where I would like a highlight bar to transform between the menu items on a nav (so the highlight smoothly goes from one menu-item to another when you hover over each menu item).

I can get it so the 'highlight' changes height and width to match the .nav-link nav-item, but I can't seem to the X and Y positioning coordinates to work using the transform property.

Any help would be awesome.

Emily

Codepen: https://codepen.io/emilychews/pen/QWjOxKz

// SELECT NAV-LINKS AND CREATE A SPAN
var navLinks = document.querySelectorAll(".nav-link"),
  theHighlight = document.createElement("span");
  
// ADD CLASS TO SPAN AND APPEND TO BODY
theHighlight.classList.add("highlight");
document.body.append(theHighlight);

// MOVE THE HIGHLIGHT TO THE NAV LINKS X/Y COORDINATES AND MATCH WIDTH AND HEIGHT
function moveHighlight() {

  var linkCoords = this.getBoundingClientRect();

  var coords = {
    width: linkCoords.width,
    height: linkCoords.height,
    top: linkCoords.top + window.scrollY,
    left: linkCoords.left + window.scrollX
  };

  theHighlight.style.width = `${coords.width}px`;
  theHighlight.style.height = `${coords.height}px`;
  theHighlight.style.transform = `translate(${coords.left}px, translate(${coords.top}px)`;
}

// CALL moveHighlight() FUNCTION ON MOUSEENTER
navLinks.forEach(a => a.addEventListener('mouseenter', moveHighlight))
.menu-items {
  display: flex;
  list-style: none;
}

.nav-link {
  margin-left: 2rem;
  display: inline-block;
  position: relative;
}

/* ADDED WITH JAVASCRIPT */
.highlight {
  top: 0;
  left: 0;
  background: red;
  transition: all 0.2s;
  display: block;
  position: absolute;
}
<body>
  <header>
    <nav class="n">
      <ul class="menu-items">
        <li><a class="nav-link" href="#">HOME</a></li>
        <li><a class="nav-link" href="#">WORK</a></li>
        <li><a class="nav-link" href="#">PROCESS</a></li>
        <li><a class="nav-link" href="#">CONTACT</a></li>
      </ul>
    </nav>
  </header>
</body>


Solution

  • Your transform string, translate(${coords.left}px, translate(${coords.top}px) is not a valid css transform value.

    When replacing the variables by actual values, the generated string will be something like: translate(80px, translate(16px).

    You instead need something like: translate(80px, 16px), this means your code needs to be:

    theHighlight.style.transform = `translate(${coords.left}px, ${coords.top}px)`;