I get an error in the code

2

In the code that is inside the if it does not work but when I take it out and put the code in the console it works, someone who can help me there:

    
asked by angel miguel gonzalez 22.09.2018 в 08:43
source

2 answers

2

Welcome to the community; I hope I can help you, but as Alfredo says, it is always good that you copy and paste your code as text, so that it is easy for us to copy and analyze.

The problem is the position where you run the script. First the script is executed and then it creates the DOM; You can use the OnLoad event, or add a listener for it, or as easy as possible, you can put the script at the end of the body, in this way.

<!DOCTYPE html>
<html>
<head>
    <title>document</title>

</head>
<body id="body">

    <script>
        let color = prompt("Elija azul con A) o amarillo con a)");
        if(color=='A'){
            document.getElementById("body").style.backgroundColor = "blue";
        }
        if(color=='a'){
            document.getElementById("body").style.backgroundColor = "yellow";
        }
    </script>
</body>

</html>

I hope it serves you.

    
answered by 22.09.2018 в 09:26
2

You can write a more professional and flexible code with the following advantages:

  • An array that manages the possible colors. This will allow other colors to be easily incorporated, simply adding them to the array (you can try to include a new pair "r" : "red" in the array, for example).
  • A controlled prompt that forces you to write valid values.
  • The variable cssColor will be defined by looking in the color array for the entered value. If it does not exist, it will give the background a default value ( gray in the code example).
  • Since body allows having an event onload , we can use add our function to that event and nothing else ...

I hope you find it useful.

function changeBackground() {
  var arrColors = {
    "A": "blue",
    "a": "yellow"
  };

  var promptMessage = "Escribe [A] para Azul o [a] para amarillo";
  var promptWrited = prompt(promptMessage, "");
  while (!promptWrited) {
    promptWrited = prompt(promptMessage, "");
  }
  var cssColor = (typeof arrColors[promptWrited] == "undefined") ? "gray" : arrColors[promptWrited];

  document.body.style.background = cssColor;
}
<body onload="changeBackground();">
    
answered by 22.09.2018 в 11:21