Search code examples
javascripthoveronmousemove

e.clientX - rect.left returns false value // vanilla JS


I'm currently building a button, which hovers in its gradient. Everything works fine, except the position of the gradient, which should be returned by e.clientX - rect.left. Hovering the button on its left edge, the result is 0% (perfect!). But hovering it on the right edge, returns something like 150%.

Thanks a lot for your help!

let btn = document.getElementById("btn");

btn.onmousemove = function (e) {
  let rect = e.target.getBoundingClientRect();
  let x = e.clientX - rect.left;
  btn.style.setProperty("--x", x + "%");
};
:root {
  --x: 0%;
}

body {
  font-family: "Open Sans", sans-serif;
  margin: 0;
}

.wrapper {
  position: absolute;
  top: calc(50% - 25px);
  left: calc(50% - 75px);
}

button {
  height: 50px;
  min-height: 50px;
  min-width: 150px;
  border: none;
  position: relative;

  background: linear-gradient(
    90deg,
    rgba(7, 22, 103, 1) 0%,
    rgba(55, 83, 198, 1) 100%
  );

  color: white;

  border-radius: 10px;

  padding: 0;
}

button:hover {
  background: none;
  cursor: pointer;
}

button::after {
  content: "";
  position: absolute;
  background: linear-gradient(
    90deg,
    rgba(7, 22, 103, 1) 0%,
    rgba(55, 83, 198, 1) var(--x),
    rgba(7, 22, 103, 1) 100%
  );

  height: 100%;
  width: 100%;
  border-radius: 10px;

  top: 0;
  left: 0;

  display: none;
  z-index: -1;
}

button:hover::after {
  display: inline;
}

span {
  margin: 0 30px;
}
  
    <link
      href="https://fonts.googleapis.com/css?family=Fjalla+One|Open+Sans&display=swap"
      rel="stylesheet"
    />
    
    <div class="wrapper">
      <button id="btn"><span>Click here</span></button>
    </div>


 


Solution

  • Finished the hover - now also the last tracked cursor position will be saved.

    let btn = document.getElementById("btn");
    
    btn.onmousemove = function (e) {
      let rect = e.target.getBoundingClientRect();
    
      let x = e.clientX - rect.left;
      btn.style.setProperty("--x", x + "px");
    };
    :root {
      --x: 0%;
    }
    
    body {
      font-family: "Open Sans", sans-serif;
      margin: 0;
    }
    
    .wrapper {
      position: absolute;
      top: calc(50% - 25px);
      left: calc(50% - 75px);
    }
    
    button {
      height: 50px;
      min-height: 50px;
      min-width: 150px;
      border: none;
      position: relative;
    
      background: linear-gradient(
        90deg,
        rgba(7, 22, 103, 1) 0%,
        rgba(55, 83, 198, 1) var(--x),
        rgba(7, 22, 103, 1) 100%
      );
    
      color: white;
    
      border-radius: 10px;
    
      padding: 0;
    }
    <link
          href="https://fonts.googleapis.com/css?family=Fjalla+One|Open+Sans&display=swap"
          rel="stylesheet"
        />
    
    <div class="wrapper">
          <button id="btn">Click here</button>
        </div>