js

[jQuery] textarea ๊ธ€์ž ์ˆ˜ count / keyup event

natrue 2021. 5. 17. 14:25
728x90
 keypress event  ์ž…๋ ฅํ•  ์ˆ˜ ์žˆ๋Š” ํ‚ค๋ณด๋“œ๋ฅผ  ๋ˆŒ๋ €์„๋•Œ ์‹คํ–‰ (ํ•œ๊ธ€ x, ์˜๋ฌธ o)
 keyup event  ๋ˆ„๋ฅธ ํ‚ค์—์„œ ์†์„ ๋—„ ๋•Œ ์‹คํ–‰.
 keydown event  ํ‚ค๋ณด๋“œ์— ์–ด๋– ํ•œ ํ‚ค๊ฐ€ ๋ˆŒ๋ ค๋„ ์‹คํ–‰ 

textarea ๊ธ€์ž ์ˆ˜๋ฅผ count ํ•˜๊ธฐ์œ„ํ•ด์„œ keyup event  ์‚ฌ์šฉ. 

<!DOCTYPE html>
<html>
<head>
<style>
.wrap {
    width: 300px;
    height: auto;
    position: relative;
    display: inline-block;
}
.wrap textarea {
    width: 100%;
    resize: none;
    min-height: 4.5em;
    line-height:1.6em;
    max-height: 9em;
}
.wrap span {
    position: absolute;
    bottom: 5px;
    right: 5px;
}
#counter {
  background:rgba(255,0,0,0.5);
  border-radius: 0.5em;
  padding: 0 .5em 0 .5em;
  font-size: 0.75em;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(function() {
  $('#content').keyup(function (e){
    var content = $(this).val();
     // CSS์˜ ๊ธธ์ด ๋‹จ์œ„ ์ค‘ em๊ณผ rem์€ ์ƒ๋Œ€์ ์œผ๋กœ ํฌ๊ธฐ๋ฅผ ์ •ํ•œ๋‹ค.
      $(this).height(((content.split('\n').length + 1) * 1.5) + 'em');
      $('#counter').html(content.length + '/600');
    });
  $('#content').keyup(); // ์ฒ˜์Œ ์„ธํŒ… 
});
</script>
</head>
<body>
<div class="wrap">
  <textarea id="content" maxlength="300"></textarea>
  <span id="counter"></span>
</div>
</body>
</html>

 

 

 

 

 

 

 

์ฐธ๊ณ  : https://zinee-world.tistory.com/237