skip to Main Content

I have a div and a textarea.

I want to achieve two things:

  1. If I select all the text in the textarea, then press backspace or delete key,
    this will add the CSS style border: 1px solid red to the div. That means: Detect if all the text was selected or not before delete.

  2. If not all of the text was selected but just a long press on backspace or delete key occurred, delete all the text, this will add the CSS style border: 1px solid red border to the div. Here I don’t want to add the CSS style or delete the text on just a short press. Just after a long key press, and all the text should be deleted add the CSS style added.

This is my code:

<div id="getcss">html contents</div>
<textarea name="new" id="message">text content</textarea>


<script>                                            
$('#message').keyup(function(e){
if (e.keyCode == 8 || e.keyCode == 46){
// Code for 1:
// if select all the text in textarea 
// then press on backspace or delete 
// will add 1px solid red border to div id="getcss" .
// Code for 2:
// if text not selected in textarea 
// and press on backspace or delete 
// and still press untill delete all the text  
// will add 1px solid red border to div id="getcss" .
}
});

</script>

2

Answers


  1. Your both condition will be covered if you apply a check of textarea data completely removed or not

    Based on check apply a class over div and write desired css for that class.

    Working snippet:

    $('#message').keyup(function(e) {
      if (e.keyCode == 8 || e.keyCode == 46) {
        if ($(this).val().length == 0) {
          $('#getcss').addClass('bordered');
        }
      }
    });
    .bordered {
      border: 1px solid red;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <div id="getcss">html contents</div>
    <br><br>
    <textarea name="new" id="message">text content</textarea>
    Login or Signup to reply.
  2. In case you ever don’t care how the textarea was emptied, you can get this behavior with CSS alone:

    #getcss:has(+ textarea:invalid) {
      border: 1px solid red;
    }
    <div id="getcss">html contents</div>
    <textarea name="new" id="message" required>text content</textarea>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search