HTML เรียกใช้ JavaScript ด้วยนะ เพราะถ้าไม่ใช้ JavaScript หน้าเว็บก็ไม่มีความเป็นไดนามิกและไม่สามารถโต้ตอบผู้ใช้งานได้
ตัวอย่าง
<!DOCTYPE html>
<html lang="th-TH">
<head>
<title>nkaub | HTML ต้องมี JavaScript</title>
</head>
<body>
<h1>JavaScript</h1>
<button type="button" onclick="document.getElementById('text').innerHTML = Date()">กดปุ่มเพื่อแสดงเวลา</button>
<p id="text"></p>
</body>
</html>
HTML เรียกใช้ JavaScript เปลี่ยนเนื้อหา
ใช้ inerHTML Property เพื่อเปลี่ยนเนื้อหา
ตัวอย่าง
<!DOCTYPE html>
<html lang="th-TH">
<head>
<title>nkaub | HTML ต้องมี JavaScript</title>
</head>
<body>
<h1>JavaScript</h1>
<button type="button" onclick="myFunction()">กดปุ่มเพื่อเปลี่ยนเนื้อหา</button>
<p id="text">ข้อความ</p>
<script>
function myFunction() {
document.getElementById("text").innerHTML = "Hello JavaScript!";
}
</script>
</body>
</html>
ใช้ JavaScript เปลี่ยนสไตล์ของ CSS
ใช้ Style fontSize Property เพื่อเปลี่ยนขนาดตัวอักษร
ใช้ Style Color Property เพื่อเปลี่ยนสี
ใช้ Style backgroundColor Property เพื่อเปลี่ยนสีพื้นหลัง
ตัวอย่าง
<!DOCTYPE html>
<html lang="th-TH">
<head>
<title>nkaub | HTML ต้องมี JavaScript</title>
</head>
<body>
<h1>JavaScript</h1>
<p id="text">ข้อความ</p>
<button type="button" onclick="myFunction()">กดปุ่มเพื่อเปลี่ยนเนื้อหา</button>
<script>
function myFunction() {
document.getElementById("text").style.fontSize = "36px";
document.getElementById("text").style.color = "red";
document.getElementById("text").style.backgroundColor = "blue";
}
</script>
</body>
</html>
วิธีเรียกใช้ JavaScript ใน HTML
สามารถทำได้ด้วย 2 วิธี
1.เขียนในแท็ก <script>
ตัวอย่าง
<!DOCTYPE html>
<html lang="th-TH">
<head>
<title>nkaub | HTML ต้องมี JavaScript</title>
</head>
<body>
<h1>JavaScript</h1>
<p id="text">ข้อความ</p>
<button type="button" onclick="myFunction()">กดปุ่มเพื่อเปลี่ยนเนื้อหา</button>
<script>
function myFunction() {
document.getElementById("text").style.fontSize = "36px";
}
</script>
</body>
</html>
2.เรียกใช้งานไฟล์ JavaScript จากภายนอก
ตัวอย่าง
<!DOCTYPE html>
<html lang="th-TH">
<head>
<title>nkaub | HTML ต้องมี JavaScript</title>
</head>
<body>
<h1>JavaScript</h1>
<p id="text">ข้อความ</p>
<button type="button" onclick="myFunction()">กดปุ่มเพื่อเปลี่ยนเนื้อหา</button>
<script src="main.js"></script>
</body>
</html>
จากตัวอย่างผมได้เขียนไฟล์ JavaScript แยกไว้ชื่อ main.js และใช้แอตทริบิวต์ src เรียกไฟล์ main.js มาใช้งาน สะดวกดีครับ เขียนที่เดียว ใช้ได้ทั้งเว็บไซต์