My code is only working inside a setInterval() or settimeout() function. I don't know how to do it using a basic javascript function. I don't want to use the setInterval function and the time is 0 ms, which is why I need to get the values before anything shows up on screen. Help me out - how to make it work without those functions.
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);
This code works well but I don't want to use setInterval or setTimeout. So I tried the code below but not working. How can I fix this and make it fast without setting any millisecond time..?
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");
}
}
CodePudding user response:
In this example I defined a function updateLogo()
that performs the update of the two CSS properties/variables. Using event listeners on both DOMContentLoaded
on document
and on resize
on window
the function will be called.
If the purpose of the setInterval()
was to update the properties when the window is resized, using the event listener is mush better.
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>