Ederson Ferreira
Ederson Ferreira

Reputation: 3

Problems with CSS changes in JavaScript

I am trying do a CSS change via JavaScript. I have a quiz site where, when the user marks the correct option, the option will become green, and when the user marks the incorrect option, the option will become red, but I have to change the color and redirect the user for another page, but the CSS change is very slow and, at certain times, doesn't work. This is my code:

CSS:

.choice{
  white-space: normal;
  word-wrap: break-word;
  margin: 20px;
  width: calc(40% + 100px);
  height: calc(10% + 10px);
  border-style: solid;
  border-color: rgba(0, 0, 0, 0.4);
  border-radius: 7px;
  background-color: rgba(255,255,255,0.6);
  cursor: pointer;
  font-size: 20px;
  transition: 0.4s;
}

JS:

function sleep(ms) {
    var d = new Date();
    var d2 = null;
    do { d2 = new Date(); }
    while(d2-d < ms);
}

function govariable(page,variable,valor,id,color) {
    document.getElementById(id).style.backgroundColor = color
    sleep(3000)
    window.location.replace(`${page}?${variable}=${valor}`)
}

Upvotes: 0

Views: 71

Answers (1)

Hecksa
Hecksa

Reputation: 2842

When you change something in the DOM (in this case, your background color) JavaScript won't update your screen until the event it is processing has finished.

This is because JavaScript runs in only one thread - it can't be looping around and around and re-displaying your background colour at the same time! It needs to finish looping first.

Instead of trying to implement a "sleep" function that will never work well in a single-threaded javascript world, you should try using setTimeout().

function govariable(page,variable,valor,id,color) {
    document.getElementById(id).style.backgroundColor = color
    setTimeout(function() {
        window.location.replace(`${page}?${variable}=${valor}`)
    }, 3000);
}

Instead of looping around again and again until time is up, at a very simplistic level this does something more like setting an internal "wake-up alarm" inside the JavaScript engine, that in 3000 milliseconds will go off, and tell JavaScript to run the code inside it. In this case, to call window.location.redirect.

Upvotes: 1

Related Questions