LoginSignup
1
1

More than 3 years have passed since last update.

JavaScriptイベント処理

Last updated at Posted at 2020-12-24

昔にjsを学んでいた事があったのですが、その時は何をしているかわからず書いており、少し触ってみたら理解しやすかったので少しアウトプットしてみました。

jsのイベント処理とは

何か特定のアクションが行われた場合にあらかじめ登録しておいた処理を実行させることができる

例として用意

<div id="web">
  <h1 id="title">学習</h1>
  <p class="content">現在JavaScript学習中、就活中</p>
  <button id="button" class="btn">クリック</button>
</div>

HTMLだけのブラウザ上での表示

スクリーンショット (3).png

ブラウザが読み込まれた時イベント処理


window.onload = function() {
    document.getElementById('title').innerText = '学習中' 
}

実行結果

スクリーンショット (4).png
window.onloadでブラウザが読み込まれた時にfunction内の処理を実行する。
ドキュメント内のid titleを取得したタグ内のテキストを設定する。

ボタンがクリックされた時イベント処理

document.getElementById("button").addEventListener('click', function()
 {document.getElementById('content').innerText = '現在JavaScript学習中、就活中、ポートフォリオ作成中'})
}

実行結果

スクリーンショット (5).png
addEventListenerで取得してきているid buttonのタグがクリックされた時、function内を実行する。
ドキュメント内のid contentのタグを取得しテキストをポートフォリオ作成中を追加した。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1