Mi código solo funciona dentro de una función setInterval() o settimeout(). No sé cómo hacerlo usando una función básica de javascript. No quiero usar la función setInterval y el tiempo es 0 ms, por lo que necesito obtener los valores antes de que aparezca algo en la pantalla. Ayúdame: cómo hacer que funcione sin esas funciones.
JAVASCRIPT
setInterval(function() { if (window.matchMedia("(min-width: 215px)").matches) { const mainwidth = window.innerWidth * 1.0; const mainheight = window.innerHeight * 1.0; document.getElementById("show-logo").style.setProperty('--set-mainwidth', mainwidth + "px"); document.getElementById("show-logo").style.setProperty('--set-mainheight', mainheight + "px"); } }, 0);Este código funciona bien pero no quiero usar setInterval o setTimeout. Así que probé el siguiente código pero no funcionó. ¿Cómo puedo arreglar esto y hacerlo rápido sin configurar ningún tiempo de milisegundos?
JAVASCRIPT
var loadcheck = initialload(); function initialload() { if (window.matchMedia("(min-width: 215px)").matches) { const mainwidth = window.innerWidth * 1.0; const mainheight = window.innerHeight * 1.0; document.getElementById("show-logo").style.setProperty('--set-mainwidth', mainwidth + "px"); document.getElementById("show-logo").style.setProperty('--set-mainheight', mainheight + "px"); } }En este ejemplo, definí una función updateLogo() que realiza la actualización de las dos propiedades/variables de CSS. Usando detectores de eventos en DOMContentLoaded en el document y en el cambio de resize en la window , se llamará a la función.
Si el propósito de setInterval() era actualizar las propiedades cuando se cambia el tamaño de la ventana, usar el detector de eventos es mucho mejor.
document.addEventListener('DOMContentLoaded', updateLogo); window.addEventListener('resize', updateLogo); function updateLogo() { if (window.matchMedia("(min-width: 215px)").matches) { const mainwidth = window.innerWidth * 1.0; const mainheight = window.innerHeight * 1.0; document.getElementById("show-logo").style.setProperty('--set-mainwidth', mainwidth + "px"); document.getElementById("show-logo").style.setProperty('--set-mainheight', mainheight + "px"); } console.log(document.getElementById("show-logo").outerHTML); } <div id="show-logo"></div>