Using Custom Variables (from within JS)

Using Custom Variables to move element according to the click on its parent.

by Konstantin Rouda

HTML

<div class="container">
  
 <div class="child"></div>
  
</div>

CSS

HTML {
  font-size: 100%;
  line-height: 1.5;
  box-sizing: border-box;
}

BODY {
  height: 100vh;
  margin: 0;
  color: #3a3d40;
}

*, *::before, *::after {
  box-sizing: inherit;
  color: inherit;
}

/*we can generate them on the :root pseudo-class*/
:root {
  --clickX: 0;
  --clickY: 0;
}

/*or custom variables can be declared right on the parent container*/
.container {
  position: relative;
  width: 90%; height: 90%;
  border: 3px solid;
  /*
  --clickX: 0;
  --clickY: 0;
  */
}

.child {
  width: 150px; height: 150px;
  background: indianred;
  transform: translate(var(--clickX, 0), var(--clickY, 0));
  transition: transform .5s ease-in-out;
}

JavaScript

const parent = document.querySelector(".container");
debugger;
const elemToMove = parent.children[0];

parent.addEventListener("click", onClick);



function onClick(e) {
	parent.style.setProperty("--clickX", e.clientX + "px");
  parent.style.setProperty("--clickY", e.clientY + "px");
}