0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

addEventListenerメソッドを使ったクリックイベント

Last updated at Posted at 2021-04-02

##「Hello world!」をクリックすると「こんにちは、世界!」と文字が変わるイベント

html
<p id="hoge">Hello world!</p>
css
#hoge {
  color: red;
  cursor: pointer;
}

###Javascript
#hogeをクリックするたびにクラスonの追加と削除を行います。
もしonが含まれていたら「こんにちは、世界!」、それ以外は「Hello world!」と表示します。

javascript
const hoge = document.querySelector('#hoge');
hoge.addEventListener('click', e => {
	hoge.classList.toggle('on');
	if( hoge.classList.contains('on') == true ){
		hoge.innerHTML = 'こんにちは、世界!';
	} else {
		hoge.innerHTML = 'Hello world!';
	}
});

###サンプル

See the Pen BapWrwM by reirei (@sugoi-reirei) on CodePen.

0
0
2

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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?