Quantcast
Channel: CSSタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8818

JavaScriptを使って文字カウントアプリを作る

$
0
0

JavaScriptを使って文字カウントアプリを作ろう!

完成見本
Image from Gyazo
はじめに、HTMLファイルを作成します。

index.html
<!DOCTYPE html><htmllang="ja"><head><metacharset="utf-8"><title>文字カウントアプリ</title></head><body><script></script></body></html>

文字を入力するテキストエリアを作ります。

index.html
<!DOCTYPE html><htmllang="ja"><head><metacharset="utf-8"><title>文字カウントアプリ</title></head><body><textareaid="text"cols="50"rows="7"></textarea><pid="count">0文字</p><script></script></body></html>

Image from Gyazo
テキストエリアができました。

このテキストエリアに文章を入力していくと、p要素に現在の文字数がリアルタイムに出力されるようにしていきます。

ここからjavascriptの記載をしていきます。
まず、テキストエリアと文字数を表示するHTML要素のID属性をgetElementById()を利用して取得します。

index.html
<script>consttext=document.getElementById("text");constcount=document.getElementById("count");</script>

取得したテキストエリアの要素にイベント処理を追加していきます。
addEventListener()を利用します。addEventListener()とは、様々なイベント処理を実行できるメソッドです。

index.html
<script>consttext=document.getElementById("text");constcount=document.getElementById("count");text.addEventListener("keyup",()=>{// 文字数をカウントする処理を記述する});</script>

イベントはkeyupです。これは、キーを押して離した瞬間に毎回イベントが実行されます。
1文字ずつ入力するたびに文字数をカウントして出力することができます。

文字数を取得するには、valueプロパティから文字列をまずは取得します。そのあとにlengthプロパティを使えば文字数を得られます。

index.html
<script>consttext=document.getElementById("text");constcount=document.getElementById("count");text.addEventListener("keyup",()=>{constinputText=text.value;count.textContent=inputText.length+"文字";});</script>

これで、文字カウントアプリは完成です。

間違い等ありましたらご指摘いただければ幸いです。
最後までご覧いただき、ありがとうございました。


Viewing all articles
Browse latest Browse all 8818

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>