JSで特定の要素を数秒後に非表示にしたり表示したりする方法【HTML,CSS,JavaScript】

JavaScript (JS) と CSSを上手く利用して、特定の要素を数秒後に表示したり、非表示にしたり出来るようにコードを書きました。

分かりやすい記事があまり無かったので、ここに置いておきます。

以下より紹介するコードでは、最初にshow-firstという要素を表示し、3秒後にはそれを非表示にします。それと同時にshow-laterという要素を表示します(最初は非表示)。

HTMLにはidとclassを付与しておく

<h1>表示・非表示テスト</h1>
<p id="show-first">最初に表示される(3秒後に非表示)</p>
<p id="show-later" class="d-none">最初は非表示(3秒後に表示される)</p>

CSSではclassにdisplay: none; を当てる

.d-none {
  display: none;
}

JavaScriptでは数秒後に2つのメソッドを実行する

2つのメソッドclassList.add() および classList.remove() を実行することでclassを追加したり削除したりします。

// 表示・非表示を切り替える要素を取得
const showFirst = document.getElementById("show-first");
const showLater = document.getElementById("show-later");
// 表示・非表示を切り替える関数
function switchDisplay() {
  showFirst.classList.add("d-none");
  showLater.classList.remove("d-none");
}
// 上記関数を3秒後に実行
setTimeout(() => {
  switchDisplay();
}, 3000);

まとめコード

HTMLソースとしてまとめると以下のコードで動作します。

<head>
  <style>
    .d-none {
		  display: none;
	  }
  </style>
</head>
<body>
  <h1>表示・非表示テスト</h1>
  <p id="show-first">最初に表示される(3秒後に非表示)</p>
  <p id="show-later" class="d-none">最初は非表示(3秒後に表示される)</p>
<script>
// 表示・非表示を切り替える要素を取得
const showFirst = document.getElementById("show-first");
const showLater = document.getElementById("show-later");
// 表示・非表示を切り替える関数
function switchDisplay() {
  showFirst.classList.add("d-none");
  showLater.classList.remove("d-none");
}
// 上記関数を3秒後に実行
setTimeout(() => {
  switchDisplay();
}, 3000);
</script>
</body>