Necesito agregar positon: fijo en .box solo si el usuario se desplaza por la página.
El punto importante aquí es que el elemento con la clase .box se genera solo después de que el usuario se desplaza por la página.
Esto es lo que se me ocurrió:
window.addEventListener('scroll', () => { const myDiv = document.querySelector('.box') if (myDiv) { if (myDiv.style.position !== 'fixed') { myDiv.style.position = 'fixed' } } })El problema con mi código es que el evento de desplazamiento ahora disparará un millón de eventos todo el tiempo y matará el rendimiento.
¿Cuál sería la forma correcta de lograr lo anterior sin activar el evento de desplazamiento una y otra vez?
Después de insertar el cuadro en el DOM, puede consultar el cuadro y agregarle el estilo de posición fija.
Si hace esto con frecuencia, aquí hay una función más general que (dado un selector, por ejemplo, .box ) esperará a que se inserte un elemento en el DOM:
function waitForElement(selector) { let element = null; let handled = false; let nextFrame; return (callback) => { function tick() { element = document.querySelector(selector); if (element === null) { nextFrame = requestAnimationFrame(tick); } if (element !== null && !handled) { handled = true; callback(element); } } cancelAnimationFrame(nextFrame); requestAnimationFrame(tick); }; }Uso:
const waitForBox = waitForElement(".box"); waitForBox((box) => { box.style.position = "fixed"; });Manifestación:
// Demo section, ignore this const plane = document.querySelector(".plane"); const box = document.createElement("div"); box.className = "box"; box.style.width = "100px"; box.style.height = "100px"; box.style.background = "crimson"; function waitForElement(selector) { let element = null; let handled = false; let nextFrame; return (callback) => { function tick() { element = document.querySelector(selector); if (element === null) { nextFrame = requestAnimationFrame(tick); } if (element !== null && !handled) { handled = true; callback(element); } } cancelAnimationFrame(nextFrame); requestAnimationFrame(tick); }; } // A function to call inside scroll callback that will // wait for the .box element to be found in the DOM const waitForBox = waitForElement(".box"); let boxAppended = false; document.addEventListener("scroll", () => { // Appending the box to the DOM, ignore this if (!boxAppended) { boxAppended = true; plane.appendChild(box); } // Callback will be fired once when the .box // element is found in the DOM waitForBox((box) => { box.style.position = "fixed"; }); }); body { padding: 0; height: 100vh; overflow: auto; } .plane { height: 200vh; } <div class="plane"></div>Por ejemplo, puede usar requestAnimationFrame() o setTimeout() para evitar que el evento de desplazamiento se active demasiadas veces.
Aquí hay un ejemplo de cómo hacer esto con requestAnimationFrame() de la documentación del evento de desplazamiento de Mozilla :
let lastKnownScrollPosition = 0; let ticking = false; function doSomething(scrollPos) { // Do something with the scroll position } document.addEventListener('scroll', function(e) { lastKnownScrollPosition = window.scrollY; if (!ticking) { window.requestAnimationFrame(function() { doSomething(lastKnownScrollPosition); ticking = false; }); ticking = true; } });