javascriptjqueryselecttext

select text in textarea , delete it by packspace/delete to add css for another element


i have a div and textarea .

i want 2 things :

1- if i select all the text in the textarea , then press on backspace or delete key , this will add css 1px solid red border to the div . this mean : detect if **all **the text selected or not before delete .

2- if not select all text but just **long **press on backspace or delete key to delete all the text , this will add css 1px solid red border to the div . here i dont want to add css if make short press and all text not deleted . just after long press and all text deleted add the css .

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 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 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>

Solution

  • 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>