この記事を読めば、HTMLボタンのonclick属性を使いこなすことができるようになります!
- ●HTMLボタンのonclick属性とは
- ●HTMLボタンのonclick属性の基本的な使い方
- ●HTMLボタンのonclick属性を使った応用例
- ○サンプルコード3:カウンター機能を実装するボタン
- ○サンプルコード4:画像の切り替えを行うボタン
- ●HTMLボタンのonclick属性の注意点
- ○イベント伝搬に関する注意点
- ○ブラウザの互換性に関する注意点
- ●HTMLボタンのonclick属性のカスタマイズ方法
- ○サンプルコード5:ボタンのスタイルを変更する
- ○サンプルコード6:複数の関数を呼び出すボタン
- ○サンプルコード7:ボタンを無効化する
- ○サンプルコード8:ボタンを非表示にする
- ○サンプルコード9:ボタンでページをリダイレクトする
- ○サンプルコード10:ボタンでテキストを追加する
- ○サンプルコード11:ボタンで画像を表示・非表示にする
- ○サンプルコード12:ボタンで入力フォームの内容をクリアする
- ○サンプルコード13:ボタンでテキストエリアにテキストを挿入する
- ○サンプルコード14:ボタンで選択されたラジオボタンの値を表示する
- ○サンプルコード15:ボタンで選択されたチェックボックスの値を表示する
- ○サンプルコード16:ボタンでセレクトボックスの選択された値を表示する
- ○サンプルコード17:ボタンでテーブルの行を追加する
- ○サンプルコード18:ボタンでフォームを送信する
- ○サンプルコード19:ボタンでフォームの入力内容を検証する
- ○サンプルコード20:ボタンでモーダルウィンドウを開く
- ○サンプルコード21:ボタンでアコーディオンメニューを開閉する
- ○サンプルコード22:ボタンでテキストエリアの行数を増減する
- ○サンプルコード23:ボタンで文字列をコピーする
- ○サンプルコード24:ボタンで画像をダウンロードする
- ○サンプルコード25:ボタンでカウンターを増減する
- ○サンプルコード26:ボタンでドラッグアンドドロップのファイル情報を表示する
- ○サンプルコード27:ボタンでCanvasに図形を描画する
- ○サンプルコード28:ボタンでLocal Storageにデータを保存・読み出し・削除する
- まとめ
●HTMLボタンのonclick属性とは
HTMLボタンのonclick属性は、ボタンがクリックされた際に実行されるJavaScriptのイベントハンドラです。
この属性を利用することで、ボタンを押すことでWebページ上でさまざまなインタラクションが可能になります。
●HTMLボタンのonclick属性の基本的な使い方
HTMLボタンのonclick属性を使うには、まず<button>タグ内にonclick属性を指定し、実行したいJavaScriptのコードを記述します。
下記に簡単なサンプルコードを示します。
○サンプルコード1:アラートを表示するボタン
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>サンプルコード1</title>
</head>
<body>
<button onclick="alert('ボタンがクリックされました!')">アラートを表示するボタン</button>
</body>
</html>
このサンプルコードでは、ボタンをクリックするとアラートが表示されます。
onclick属性にはalert('ボタンがクリックされました!')
というJavaScriptコードが指定されています。
○サンプルコード2:テキストを変更するボタン
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>サンプルコード2</title>
<script>
function changeText() {
document.getElementById('sampleText').innerHTML = 'テキストが変更されました!';
}
</script>
</head>
<body>
<p id="sampleText">ここにあるテキストが変更されます。</p>
<button onclick="changeText()">テキストを変更するボタン</button>
</body>
</html>
このサンプルコードでは、ボタンをクリックすると指定したテキストが変更されます。
onclick属性にはchangeText()
というJavaScript関数が指定されています。
●HTMLボタンのonclick属性を使った応用例
HTMLボタンのonclick属性を使って、さまざまな応用例を作成することができます。
下記にいくつかの応用例を示します。
○サンプルコード3:カウンター機能を実装するボタン
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>サンプルコード3</title>
<script>
let count = 0;
function increaseCounter() {
count++;
document.getElementById('counter').innerHTML = 'カウント:' + count;
}
</script>
</head>
<body>
<p id="counter">カウント:0</p>
<button onclick="increaseCounter()">カウントアップボタン</button>
</body>
</html>
このサンプルコードでは、ボタンをクリックするとカウンターが1ずつ増える機能を実装しています。
onclick属性にはincreaseCounter()
というJavaScript関数が指定されています。
○サンプルコード4:画像の切り替えを行うボタン
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>サンプルコード4</title>
<script>
function changeImage() {
const imgElement = document.getElementById('sampleImage');
const currentSrc = imgElement.src;
if (currentSrc.endsWith('image1.jpg')) {
imgElement.src = 'image2.jpg';
} else {
imgElement.src = 'image1.jpg';
}
}
</script>
</head>
<body>
<img id="sampleImage" src="image1.jpg" alt="サンプル画像">
<button onclick="changeImage()">画像を切り替えるボタン</button>
</body>
</html>
このサンプルコードでは、ボタンをクリックすると画像が切り替わる機能を実装しています。
onclick属性にはchangeImage()
というJavaScript関数が指定されています。
実際に動作させる場合は、適切な画像ファイル名に変更してください。
●HTMLボタンのonclick属性の注意点
HTMLボタンのonclick属性を使う際に注意すべき点がいくつかあります。
主な注意点を下記に示します。
○イベント伝搬に関する注意点
イベント伝搬は、HTML要素がネストされている際に、イベントが親要素から子要素へと伝わっていくことです。
onclick属性を使う際には、イベント伝搬が発生しないように注意が必要です。
イベント伝搬を防ぐためには、JavaScriptのevent.stopPropagation()
関数を使用します。
○ブラウザの互換性に関する注意点
HTMLボタンのonclick属性は、ほとんどのブラウザでサポートされていますが、一部の古いブラウザでは正しく動作しないことがあります。
そのため、対象となるブラウザの範囲を明確にし、必要に応じて代替案を用意することが重要です。
●HTMLボタンのonclick属性のカスタマイズ方法
HTMLボタンのonclick属性をカスタマイズする方法もいくつかあります。
下記に主なカスタマイズ方法を示します。
○サンプルコード5:ボタンのスタイルを変更する
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>サンプルコード5</title>
<style>
.btn {
background-color: blue;
color: white;
font-size: 16px;
padding: 10px 20px;
}
</style>
</head>
<body>
<button class="btn" onclick="alert('カスタマイズされたボタンがクリックされました!')">カスタマイズされたボタン</button>
</body>
</html>
○サンプルコード6:複数の関数を呼び出すボタン
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>サンプルコード6</title>
<script>
function firstFunction() {
console.log('最初の関数が呼び出されました!');
}
function secondFunction() {
console.log('二番目の関数が呼び出されました!');
}
</script>
</head>
<body>
<button onclick="firstFunction(); secondFunction();">複数の関数を呼び出すボタン</button>
</body>
</html>
○サンプルコード7:ボタンを無効化する
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>サンプルコード7</title>
<script>
function disableButton() {
document.getElementById('sampleButton').disabled = true;
}
</script>
</head>
<body>
<button id="sampleButton" onclick="disableButton()">無効化するボタン</button>
</body>
</html>
○サンプルコード8:ボタンを非表示にする
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>サンプルコード8</title>
<script>
function hideButton() {
document.getElementById('sampleButton').style.display = 'none';
}
</script>
</head>
<body>
<button id="sampleButton" onclick="hideButton()">非表示にするボタン</button>
</body>
</html>
このサンプルコードでは、ボタンをクリックすると非表示になる機能を実装しています。
○サンプルコード9:ボタンでページをリダイレクトする
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>サンプルコード9</title>
<script>
function redirectToPage() {
window.location.href = 'https://www.example.com';
}
</script>
</head>
<body>
<button onclick="redirectToPage()">ページをリダイレクトするボタン</button>
</body>
</html>
このサンプルコードでは、ボタンをクリックすると指定したURLにリダイレクトする機能を実装しています。
○サンプルコード10:ボタンでテキストを追加する
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>サンプルコード10</title>
<script>
function addText() {
const p = document.createElement('p');
p.textContent = 'ボタンで追加されたテキスト';
document.body.appendChild(p);
}
</script>
</head>
<body>
<button onclick="addText()">テキストを追加するボタン</button>
</body>
</html>
○サンプルコード11:ボタンで画像を表示・非表示にする
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>サンプルコード11</title>
<script>
function toggleImage() {
const img = document.getElementById('sampleImage');
img.style.display = img.style.display === 'none' ? 'block' : 'none';
}
</script>
</head>
<body>
<button onclick="toggleImage()">画像を表示・非表示にするボタン</button>
<img id="sampleImage" src="sample_image.jpg" alt="サンプル画像" style="display: none;">
</body>
</html>
○サンプルコード12:ボタンで入力フォームの内容をクリアする
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>サンプルコード12</title>
<script>
function clearInput() {
document.getElementById('sampleInput').value = '';
}
</script>
</head>
<body>
<input id="sampleInput" type="text" placeholder="テキストを入力">
<button onclick="clearInput()">入力をクリアするボタン</button>
</body>
</html>
○サンプルコード13:ボタンでテキストエリアにテキストを挿入する
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>サンプルコード13</title>
<script>
function insertText() {
document.getElementById('sampleTextArea').value = 'ボタンで挿入されたテキスト';
}
</script>
</head>
<body>
<textarea id="sampleTextArea" rows="4" cols="50"></textarea>
<button onclick="insertText()">テキストを挿入するボタン</button>
</body>
</html>
○サンプルコード14:ボタンで選択されたラジオボタンの値を表示する
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>サンプルコード14</title>
<script>
function showSelectedRadioValue() {
const radios = document.getElementsByName('sampleRadio');
let selectedValue;
for (const radio of radios) {
if (radio.checked) {
selectedValue = radio.value;
break;
}
}
document.getElementById('result').textContent = `選択されたラジオボタンの値: ${selectedValue}`;
}
</script>
</head>
<body>
<label><input type="radio" name="sampleRadio" value="A">A</label>
<label><input type="radio" name="sampleRadio" value="B">B</label>
<label><input type="radio" name="sampleRadio" value="C">C</label>
<button onclick="showSelectedRadioValue()">選択された値を表示するボタン</button>
<p id="result"></p>
</body>
</html>
○サンプルコード15:ボタンで選択されたチェックボックスの値を表示する
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>サンプルコード15</title>
<script>
function showSelectedCheckboxValues() {
const checkboxes = document.getElementsByName('sampleCheckbox');
const selectedValues = [];
for (const checkbox of checkboxes) {
if (checkbox.checked) {
selectedValues.push(checkbox.value);
}
}
document.getElementById('result').textContent = `選択されたチェックボックスの値: ${selectedValues.join(', ')}`;
}
</script>
</head>
<body>
<label><input type="checkbox" name="sampleCheckbox" value="A">A</label>
<label><input type="checkbox" name="sampleCheckbox" value="B">B</label>
<label><input type="checkbox" name="sampleCheckbox" value="C">C</label>
<button onclick="showSelectedCheckboxValues()">選択された値を表示するボタン</button>
<p id="result"></p>
</body>
</html>
○サンプルコード16:ボタンでセレクトボックスの選択された値を表示する
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>サンプルコード16</title>
<script>
function showSelectedOptionValue() {
const select = document.getElementById('sampleSelect');
const selectedValue = select.options[select.selectedIndex].value;
document.getElementById('result').textContent = `選択されたオプションの値: ${selectedValue}`;
}
</script>
</head>
<body>
<select id="sampleSelect">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
<button onclick="showSelectedOptionValue()">選択された値を表示するボタン</button>
<p id="result"></p>
</body>
</html>
○サンプルコード17:ボタンでテーブルの行を追加する
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>サンプルコード17</title>
<script>
function addTableRow() {
const table = document.getElementById('sampleTable');
const newRow = table.insertRow(-1);
newRow.insertCell(-1).textContent = '新しいセル1';
newRow.insertCell(-1).textContent = '新しいセル2';
}
</script>
</head>
<body>
<table id="sampleTable" border="1">
<tr>
<td>セル1</td>
<td>セル2</td>
</tr>
</table>
<button onclick="addTableRow()">行を追加するボタン</button>
</body>
</html>
○サンプルコード18:ボタンでフォームを送信する
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>サンプルコード18</title>
<script>
function submitForm() {
document.getElementById('sampleForm').submit();
}
</script>
</head>
<body>
<form id="sampleForm" action="submit.html" method="post">
<label for="name">名前:</label>
<input id="name" type="text" name="name">
</form>
<button onclick="submitForm()">フォームを送信するボタン</button>
</body>
</html>
○サンプルコード19:ボタンでフォームの入力内容を検証する
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>サンプルコード19</title>
<script>
function validateForm() {
const input = document.getElementById('name');
if (input.value === '') {
alert('名前を入力してください。');
return false;
}
return true;
}
</script>
</head>
<body>
<form id="sampleForm" action="submit.html" method="post" onsubmit="return validateForm();">
<label for="name">名前:</label>
<input id="name" type="text" name="name">
<button type="submit">フォームを送信するボタン</button>
</form>
</body>
</html>
○サンプルコード20:ボタンでモーダルウィンドウを開く
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>サンプルコード20</title>
<style>
.modal {
display: none;
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgba(0, 0, 0, 0.4);
}
.modal-content {
background-color: #fefefe;
margin: 15% auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
</style>
<script>
function openModal() {
document.getElementById('myModal').style.display = 'block';
}
function closeModal() {
document.getElementById('myModal').style.display = 'none';
}
</script>
</head>
<body>
<button onclick="openModal()">モーダルウィンドウを開くボタン</button>
<div id="myModal" class="modal">
<div class="modal-content">
<span onclick="closeModal()">×</span>
<p>モーダルウィンドウの内容</p>
</div>
</div>
</body>
</html>
○サンプルコード21:ボタンでアコーディオンメニューを開閉する
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>サンプルコード21</title>
<style>
.accordion {
background-color: #eee;
cursor: pointer;
padding: 18px;
width: 100%;
text-align: left;
border: none;
outline: none;
transition: 0.4s;
}
.panel {
padding: 0 18px;
display: none;
background-color: white;
overflow: hidden;
}
</style>
<script>
function toggleAccordion(button) {
button.classList.toggle("active");
const panel = button.nextElementSibling;
panel.style.display = panel.style.display === 'block' ? 'none' : 'block';
}
</script>
</head>
<body>
<button class="accordion" onclick="toggleAccordion(this)">セクション1</button>
<div class="panel">
<p>セクション1の内容</p>
</div>
<button class="accordion" onclick="toggleAccordion(this)">セクション2</button>
<div class="panel">
<p>セクション2の内容</p>
</div>
<button class="accordion" onclick="toggleAccordion(this)">セクション3</button>
<div class="panel">
<p>セクション3の内容</p>
</div>
</body>
</html>
○サンプルコード22:ボタンでテキストエリアの行数を増減する
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>サンプルコード22</title>
<script>
function increaseRows() {
const textarea = document.getElementById('sampleTextarea');
textarea.rows += 1;
}
function decreaseRows() {
const textarea = document.getElementById('sampleTextarea');
if (textarea.rows > 1) {
textarea.rows -= 1;
}
}
</script>
</head>
<body>
<textarea id="sampleTextarea" rows="4" cols="50"></textarea>
<button onclick="increaseRows()">行数を増やすボタン</button>
<button onclick="decreaseRows()">行数を減らすボタン</button>
</body>
</html>
○サンプルコード23:ボタンで文字列をコピーする
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>サンプルコード23</title>
<script>
function copyText() {
const text = document.getElementById('sampleText').innerText;
const textarea = document.createElement('textarea');
textarea.textContent = text;
document.body.appendChild(textarea);
textarea.select();
document.execCommand('copy');
document.body.removeChild(textarea);
alert('テキストがコピーされました: ' + text);
}
</script>
</head>
<body>
<p id="sampleText">コピーされるテキスト</p>
<button onclick="copyText()">テキストをコピーするボタン</button>
</body>
</html>
○サンプルコード24:ボタンで画像をダウンロードする
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>サンプルコード24</title>
<script>
function downloadImage() {
const img = document.getElementById('sampleImage');
const a = document.createElement('a');
a.href = img.src;
a.download = 'sample-image.jpg';
a.click();
}
</script>
</head>
<body>
<img id="sampleImage" src="sample-image.jpg" alt="サンプル画像" />
<button onclick="downloadImage()">画像をダウンロードするボタン</button>
</body>
</html>
○サンプルコード25:ボタンでカウンターを増減する
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>サンプルコード25</title>
<script>
let counter = 0;
function increaseCounter() {
counter++;
document.getElementById('counterDisplay').textContent = counter;
}
function decreaseCounter() {
counter--;
document.getElementById('counterDisplay').textContent = counter;
}
</script>
</head>
<body>
<p id="counterDisplay">0</p>
<button onclick="increaseCounter()">カウンターを増やすボタン</button>
<button onclick="decreaseCounter()">カウンターを減らすボタン</button>
</body>
</html>
○サンプルコード26:ボタンでドラッグアンドドロップのファイル情報を表示する
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>サンプルコード26</title>
<style>
#dropArea {
width: 300px;
height: 200px;
border: 1px solid #000;
}
</style>
<script>
function onDragOver(event) {
event.preventDefault();
}
function onDrop(event) {
event.preventDefault();
const files = event.dataTransfer.files;
for (let i = 0; i < files.length; i++) {
const file = files[i];
const listItem = document.createElement('li');
listItem.textContent = `ファイル名: ${file.name}, サイズ: ${file.size}バイト`;
document.getElementById('fileList').appendChild(listItem);
}
}
</script>
</head>
<body>
<div id="dropArea" ondragover="onDragOver(event)" ondrop="onDrop(event)">
ドラッグアンドドロップするエリア
</div>
<ul id="fileList"></ul>
</body>
</html>
○サンプルコード27:ボタンでCanvasに図形を描画する
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>サンプルコード27</title>
<script>
function drawRectangle() {
const canvas = document.getElementById('sampleCanvas');
const ctx = canvas.getContext('2d');
ctx.fillStyle = 'red';
ctx.fillRect(10, 10, 100, 50);
}
function drawCircle() {
const canvas = document.getElementById('sampleCanvas');
const ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.arc(200, 30, 25, 0, 2 * Math.PI);
ctx.fillStyle = 'blue';
ctx.fill();
}
</script>
</head>
<body>
<canvas id="sampleCanvas" width="300" height="100" style="border:1px solid #000;"></canvas>
<button onclick="drawRectangle()">四角形を描画するボタン</button>
<button onclick="drawCircle()">円を描画するボタン</button>
</body>
</html>
○サンプルコード28:ボタンでLocal Storageにデータを保存・読み出し・削除する
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>サンプルコード28</title>
<script>
function saveData() {
const input = document.getElementById('inputData');
localStorage.setItem('sampleData', input.value);
input.value = '';
alert('データが保存されました。');
}
function loadData() {
const data = localStorage.getItem('sampleData');
if (data) {
document.getElementById('outputData').textContent = data;
} else {
alert('保存されたデータがありません。');
}
}
function deleteData() {
localStorage.removeItem('sampleData');
document.getElementById('outputData').textContent = '';
alert('データが削除されました。');
}
</script>
</head>
<body>
<input type="text" id="inputData" placeholder="データを入力">
<button onclick="saveData()">データを保存するボタン</button>
<button onclick="loadData()">データを読み出すボタン</button>
<button onclick="deleteData()">データを削除するボタン</button>
<p id="outputData"></p>
</body>
</html>
まとめ
これらのサンプルコードを参考にして、HTMLボタンのonclick属性を使ったさまざまな機能を実装してみてください。
必要に応じて、さらにサンプルコードを追加することもできます。
この記事を通じて、HTMLボタンのonclick属性を効果的に使用できるようになることを期待しています。