0

I want to change the color of the button dependently on some condition.

In pseudo code it looks like this:

if(condition){
    myelememt.background = "something"
}

But it should be checked and applied before the page is loaded.

Thank you!

obgire
  • 25
  • 6
  • 1
    Does this answer your question? [Changing button color programmatically](https://stackoverflow.com/questions/1819878/changing-button-color-programmatically) – Ahmet Firat Keler Apr 10 '22 at 12:12
  • _"But it should be checked and applied before the page is loaded."_. How can you change the colour of a button that doesn't exist yet? – Andy Apr 10 '22 at 12:50
  • @Andy I meant that it should be resolved on the fly, but not after the page is loaded. It should not be visible for user – obgire Apr 11 '22 at 10:41

1 Answers1

0

Since you want it to apply the style before DOM paints, you can use DOMContentLoaded event, since this event fires as soon as the DOM nodes have finished loading, but before all assets, styles, etc... have been loaded.

Something like this should make it:

const condition = true;
document.addEventListener('DOMContentLoaded', (event) => {
  const button = document.querySelector('button');
  if (condition) button.style.background = 'red';
});
<html>
  <head>
    <meta charset="UTF-8" />
    <script src="script.js"></script>
    <link rel="stylesheet" type="text/css" href="styles.css" />
  </head>
  <body>
    <button>CLICK</button>
  </body>
</html>
Cesare Polonara
  • 3,473
  • 1
  • 9
  • 19