はじめに
この記事を読めば、JavaScript埋め込みを簡単に学べるようになります。
初心者の方でも分かりやすいように、実践的なサンプルコードを交えて解説していきます。
JavaScript埋め込みとは
JavaScript埋め込みとは、ウェブページにJavaScriptコードを埋め込むことで、ページにインタラクティブな機能を追加する方法です。
例えば、ボタンをクリックした際のアクションや、アニメーション効果などを実現することができます。
JavaScript埋め込みの基本
○HTMLへの埋め込み方法
JavaScriptコードは、HTMLの<script>
タグを使用して埋め込みます。
<script>
タグは、<head>
タグ内や<body>
タグ内に配置することができます。
下記のように記述します。
<!DOCTYPE html>
<html>
<head>
<script>
// ここにJavaScriptコードを記述
</script>
</head>
<body>
<!-- 省略 -->
</body>
</html>
○外部ファイルの読み込み
JavaScriptコードが長くなる場合や、複数のページで共通のコードを使いたい場合は、外部ファイルにコードを記述し、<script>
タグで読み込むことができます。
下記のように記述します。
<!DOCTYPE html>
<html>
<head>
<script src="外部ファイル.js"></script>
</head>
<body>
<!-- 省略 -->
</body>
</html>
実践的なサンプルコード10選
○サンプルコード1:アラート表示
<!DOCTYPE html>
<html>
<head>
<script>
function showAlert() {
alert("こんにちは、世界!");
}
</script>
</head>
<body>
<button onclick="showAlert()">クリックしてください</button>
</body>
</html>
○サンプルコード2:ボタンクリックでテキスト変更
<!DOCTYPE html>
<html>
<head>
<script>
function changeText() {
document.getElementById("target").innerHTML = "こんにちは、世界!";
}
</script>
</head>
<body>
<p id="target">ここにテキストが表示されます。</p>
<button onclick="changeText()">クリックしてください</button>
</body>
</html>
○サンプルコード3:画像の切り替え
<!DOCTYPE html>
<html>
<head>
<script>
function changeImage() {
var img = document.getElementById("myImage");
img.src = img.src.endsWith("img1.jpg") ? "img2.jpg" : "img1.jpg";
}
</script>
</head>
<body>
<img id="myImage" src="img1.jpg" alt="画像" onclick="changeImage()">
</body>
</html>
○サンプルコード4:フォーム入力チェック
<!DOCTYPE html>
<html>
<head>
<script>
function checkForm() {
var input = document.getElementById("myInput");
if (input.value.length < 5) {
alert("5文字以上で入力してください。");
return false;
}
return true;
}
</script>
</head>
<body>
<form onsubmit="return checkForm()">
<input id="myInput" type="text">
<button type="submit">送信</button>
</form>
</body>
</html>
○サンプルコード5:マウスオーバーで画像拡大
<!DOCTYPE html>
<html>
<head>
<style>
#myImage {
width: 200px;
height: auto;
transition: all 0.5s;
}
#myImage:hover {
transform: scale(1.2);
}
</style>
</head>
<body>
<img id="myImage" src="sample.jpg" alt="サンプル画像">
</body>
</html>
○サンプルコード6:ドロップダウンメニュー
<!DOCTYPE html>
<html>
<head>
<style>
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
padding: 12px 16px;
z-index: 1;
}
.dropdown:hover .dropdown-content {
display: block;
}
</style>
</head>
<body>
<div class="dropdown">
<button>メニュー</button>
<div class="dropdown-content">
<p><a href="#">リンク1</a></p>
<p><a href="#">リンク2</a></p>
<p><a href="#">リンク3</a></p>
</div>
</div>
</body>
</html>
○サンプルコード7:スライドショー
<!DOCTYPE html>
<html>
<head>
<style>
.slideshow {
width: 100%;
height: 400px;
overflow: hidden;
position: relative;
}
.slideshow img {
width: 100%;
height: auto;
position: absolute;
opacity: 0;
transition: opacity 1s;
}
.slideshow img.active {
opacity: 1;
}
</style>
<script>
window.addEventListener("DOMContentLoaded", function () {
var images = document.querySelectorAll(".slideshow img");
var currentIndex = 0;
images[currentIndex].classList.add("active");
setInterval(function () {
images[currentIndex].classList.remove("active");
currentIndex = (currentIndex + 1) % images.length;
images[currentIndex].classList.add("active");
}, 3000);
});
</script>
</head>
<body>
<div class="slideshow">
<img src="img1.jpg" alt="画像1" class="active">
<img src="img2.jpg" alt="画像2">
<img src="img3.jpg" alt="画像3">
</div>
</body>
</html>
○サンプルコード8:モーダルウィンドウ
<!DOCTYPE html>
<html>
<head>
<style>
.modal {
display: none;
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.4);
}
.modal-content {
background-color: #fefefe;
margin: 15% auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
</style>
<script>
function showModal() {
document.getElementById("myModal").style.display = "block";
}
function closeModal() {
document.getElementById("myModal").style.display = "none";
}
</script>
</head>
<body>
<button onclick="showModal()">クリックしてモーダルを開く</button>
<div id="myModal" class="modal">
<div class="modal-content">
<span class="close" onclick="closeModal()">×</span>
<p>モーダルウィンドウの内容</p>
</div>
</div>
</body>
</html>
○サンプルコード9:アコーディオンメニュー
<!DOCTYPE html>
<html>
<head>
<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");
var panel = button.nextElementSibling;
if (panel.style.display === "block") {
panel.style.display = "none";
} else {
panel.style.display = "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>
○サンプルコード10:タブ切り替え
<!DOCTYPE html>
<html>
<head>
<style>
.tab {
overflow: hidden;
background-color: #f1f1f1;
}
.tab button {
background-color: inherit;
float: left;
border: none;
outline: none;
cursor: pointer;
padding: 14px 16px;
transition: 0.3s;
font-size: 17px;
}
.tab button:hover {
background-color: #ddd;
}
.tab button.active {
background-color: #ccc;
}
.tabcontent {
display: none;
padding: 6px 12px;
border-top: none;
}
</style>
<script>
function openTab(event, tabName) {
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" active", "");
}
document.getElementById(tabName).style.display = "block";
event.currentTarget.className += " active";
}
</script>
</head>
<body>
<div class="tab">
<button class="tablinks" onclick="openTab(event, 'Tab1')">Tab1</button>
<button class="tablinks" onclick="openTab(event, 'Tab2')">Tab2</button>
<button class="tablinks" onclick="openTab(event, 'Tab3')">Tab3</button>
</div>
<div id="Tab1" class="tabcontent">
<h3>Tab1</h3>
<p>Tab1の内容</p>
</div>
<div id="Tab2" class="tabcontent">
<h3>Tab2</h3>
<p>Tab2の内容</p>
</div>
<div id="Tab3" class="tabcontent">
<h3>Tab3</h3>
<p>Tab3の内容</p>
</div>
</body>
</html>
まとめ
この記事を読めば、JavaScriptの埋め込みに関する基本的な使い方から応用例まで、10種類の実践的なサンプルコードを学ぶことができます。
これらのサンプルコードを参考に、自分のプロジェクトに取り入れたり、カスタマイズしてみたりして、効果的なWebサイトを作成してください。
JavaScriptは非常に柔軟で強力な言語ですので、さらに深く学んでいくことで、より多くの可能性を開拓することができるでしょう。