skip to Main Content

I need to update the x and y position where a user clicks to populate the top and left properties of a div:

.dataCardAbsolute {
  position: absolute;
  top: 100px;
  left: 300px;
  overflow: auto;
}

  React.useEffect(() => {
    document.body.addEventListener('click', (event) => { setPosition([event.pageX, event.pageY]) })
  }, []);

  <div
  className={{styles.`dataCardAbsolute-${}`}} //an attempt...
  className={styles.dataCardAbsolute}         
 >

How do I pass the updated position to the css file?

2

Answers


  1. You can try using CSS variables (like the ones you usually set in your :root declaration).

    With CSS variables you can even set "default" variables by writing them statically in the "style" attribute of your div.

    Here’s a little example 😉 !

    document.addEventListener("DOMContentLoaded", () => {
      let button = document.getElementById("buttonID");
      let item = document.getElementById("itemID");
       
       let toggle = false;
    
      button.addEventListener("click", () => {
        item.style = toggle ? "--radius: 50%;" : "--radius: 20%;";
        toggle = !toggle;
      });
    });
    html, body {
      width: 100%;
      height: 100%;
    }
    
    .button {
      background-color: aliceblue;
      width: 20%;
      height: 20%;
    }
    
    .item {
      border-radius: var(--radius);
      
      background-color: green;
      width: 30%;
      height: 40%;
    }
    <button class="button" id="buttonID">Resize the item</button>
    <div class="item" id="itemID" style="--radius: 50%;"></div>
    Login or Signup to reply.
  2. I’m assuming the state for the setter function is position so is the code to update it, you would have to update it via inline styles, this would be the easiest route.

     <div
          className={styles.dataCardAbsolute}
          style={{ top: `${position.top}px`, left: `${position.left}px` }}
        >
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search