Detect when the cursor is no longer in the textarea with JavaScript

Viewed 188

What I want to do is an HTML file which detects if the textArea has something written or not. To show it, I change the background color, so grey color is used when the textArea is empty and white when it has something written on it.

With this end, I developed this code:

function prueba() {
    if (document.getElementById("text_1_3").value != "") {
        document.getElementById("text_1_3").style.background = "white";
    } else {
        document.getElementById("text_1_3").style.background = "rgb(174,170,170)";
    }
}
Text Area: <textarea id="text_1_3" style="background-color:rgb(174,170,170)" onclick="prueba();"></textarea>

The main problem I have with this code is that to update the background-color, I always have to click on the textArea. And what I would like is that when I finished typing whatever in the textArea and I click on any part of the page (even if there is not a reference, button..., lets say in "plain text"), the background color is updated.

2 Answers

Just use CSS to change the color, no JavaScript is needed.

textarea:focus {
  background-color: #FFF;
}
 
textarea { 
  background-color: rgb(174,170,170)
}
<textarea></textarea>

If you want to do it with JavaScript, you should be using focus and blur event listeners, not click.

var ta = document.querySelector("textarea")
ta.addEventListener("focus", function () {
  ta.style.backgroundColor = "#FFF"
})

ta.addEventListener("blur", function () {
  ta.style.backgroundColor = "rgb(174,170,170)"
})
<textarea></textarea>

Based on the answer of @epascarello and doing some changes, I get what I wanted! Here is the code:

<html>
Text Area: <textarea id="text_1_3" style="background-color:rgb(174,170,170)" onclick="prueba();"></textarea>
</html>
<script>
    var ta = document.querySelector("textarea")     
    ta.addEventListener("blur", function () {
        if (document.getElementById("text_1_3").value != "") {
            document.getElementById("text_1_3").style.background = "white";
        }
        else{
            document.getElementById("text_1_3").style.background = "rgb(174,170,170)";
        }
    })
</script>
Related