Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

232
Visualizações
Can't I move element by using "element.style.top = window.scrollY"?

I'm trying to make some kind of floating input element, making it follows the scroll. finally I made it and there is code below.

What I am wondering about is if i change "setText(window.scrollY)" to "document.querySelector(".code).style.top = window.scrollY" it doesn't give me the same result. I think it is same code but later code doesn't work. Can anybody tell me why? thank you

import React, { useState } from "react";

function Input() {
  const [scroll, setScroll] = useState(0);
  
  window.addEventListener(
    "scroll",
    function () {
      if (typeof document.querySelector(".code") === "undefined") {
        alert("TT");
      } else {
        setScroll(window.scrollY);              // *this part
      }
    },
    { passive: true }
  );

  return (
    <input
      style={{
        top: text
      }}
      className="code"
      autoComplete="on"
      placeholder="Write code please"
    />
  );
}

export default Input;
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

 setScroll(window.scrollY+"px");  
about 4 years ago · Juan Pablo Isaza Relatório

0

Use the useRef() hook instead of document.querySelector(".code"). React works with virtual DOM, so when document.querySelector(".code") runs, the rea DOM would not be available yet. But you can use useRef to grab the virtual DOM and perform your manipulations on it. You can access the element with the ref's .current property.

Secondly, the scroll event handler would need to be wrapped in React's useEffect hook, to ensure it is added when the component mounts.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda