LoginSignup
0
1

More than 3 years have passed since last update.

event.preventDefault() を最低限理解する

Last updated at Posted at 2020-03-12

背景

event.preventDefault() というものをよく見かけるけどコレ何?

一言で

DOMイベントを止めるもの
Prevent : 防ぐ
Default : デフォルト
デフォルトのイベントをさせないよ

動作確認ファイル

index.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>preventDefault</title>
</head>
<body>
    <a id="google" href="https://google.com">Google</a>
    <script src="app.js"></script>
</body>
</html>
app.js
const google = document.getElementById("google")

google.addEventListener("click", () => {
    event.preventDefault() /* これ */
    console.log("link先への遷移イベントを防いだよ")
})

今回のファイルで何を確認するのか

aタグをクリックするとリンク先に飛ぶというイベントが起こる。これを止める。

preventDefault.png

こんな感じ

終わり

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