Template Literals are not adding value together

Viewed 31

I think I am running into a Template Literal issue. I am trying to get some values, add them together to make a new value and then apply it to the target element. But when I add them together, no value is returned.

const el = document.querySelector('.row[data-target="row-offset"]');
const distanceFromLeft = el.offsetLeft;
const paddingLeft = window.getComputedStyle(el, null).getPropertyValue('padding-left');
const target = document.querySelector('#hero-carousel .flickity-page-dots');

target.style.left = `${distanceFromLeft + paddingLeft}px`;

I have alerted out the querySelector elements and thus know I am targeting them correctly. Console logging both distanceFromLeft and paddingLeft results in values being outputted.

Therefore I am left thinking there is something wrong with my Template Literal. No errors are being reported.

I have mocked up the issues here

The expected result is for target to have the same value as el.

1 Answers

That's because the window.getComputedStyle(el, null).getPropertyValue("padding-left") will output the value with px for example 16px, so you need to get the value as a number with parseFloat() method.

const paddingLeft = parseFloat(window
  .getComputedStyle(el, null)
  .getPropertyValue("padding-left"));

const el = document.querySelector('.row[data-target="row-offset"]');
const distanceFromLeft = el.offsetLeft;
const paddingLeft = parseFloat(window
  .getComputedStyle(el, null)
  .getPropertyValue("padding-left"));
const target = document.querySelector("#hero-carousel .flickity-page-dots");

target.style.left = `${distanceFromLeft + paddingLeft}px`;

// if (target) {
//   alert("Element exists");
// } else {
//   alert("Element does not exist");
// }
console.log(distanceFromLeft);
console.log(paddingLeft);
body {
  font-family: sans-serif;
  position: relative;
}

.row {
  display: block;
  background-color: pink;
  width: 90%;
  height: 100px;
  margin: 0 auto;
}

.flickity-page-dots {
  display: block;
  background-color: blue;
  width: 20%;
  position: absolute;
  left: 0;
  height: 100px;
}
<!DOCTYPE html>
<html>
  <head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
    <link rel="stylesheet" href="src/styles.css" type="text/css" />
  </head>

  <body>
    <div id="hero-carousel">
      <div class="row" data-target="row-offset"></div>
      <div class="flickity-page-dots"></div>
    </div>

    <script src="src/index.js"></script>
  </body>
</html>

Related