0

I made an onclick with js where it toggles the color of a textarea's text between red and green.(starts as red) Any ideas why the onclick starts to work after the second click but not right away ?

function todocheckdone(){
  var el = document.getElementById("task1");   
    
if (el.style.color === "red"){
    el.style.color = "green";
    }
  
  else{
    el.style.color = "red";
}}
#todosnumbering{
   font-size: 18px;
    top: 18px;
    left: 10px;
    position: absolute;
}
#task1{
    font-size: 18px;
    text-align: left;
    color: red;
    font-size: 18px;
    width: 358px;
    height: 40px;
    top: 16px;
    left: 30px;
    position: absolute;
    background: white;
   
    }
#todocheck1{
    
    top: 20px;
    left: 406px;
    position: absolute;
}
<html>
<body>
<button type="button" id="todocheck1" onclick="todocheckdone()"
>✓</button>
<div id="todosnumbering">1.</div>
<textarea id="task1">THIS TEXT TOGGLES BETWEEN GREEN AND RED</textarea>
</body>
</html>

1 Answers1

1

Checking the .style.someProp of an element will only give you style properties assigned directly to the element. Since the element doesn't have the color property directly assigned to it initially, accessing .style.color gives you the empty string the first time the function runs.

Instead of setting the style directly, I'd toggle a class:

function todocheckdone() {
  var el = document.getElementById("task1");
  el.classList.toggle('green');
}
#todosnumbering {
  font-size: 18px;
  top: 18px;
  left: 10px;
  position: absolute;
}

#task1 {
  font-size: 18px;
  text-align: left;
  color: red;
  font-size: 18px;
  width: 358px;
  height: 40px;
  top: 16px;
  left: 30px;
  position: absolute;
  background: white;
}

#task1.green {
  color: green;
}

#todocheck1 {
  top: 20px;
  left: 406px;
  position: absolute;
}
<button type="button" id="todocheck1" onclick="todocheckdone()">✓</button>
<div id="todosnumbering">1.</div>
<textarea id="task1">THIS TEXT TOGGLES BETWEEN GREEN AND RED</textarea>
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320