Introduction
How to use JavaScript function in HTML. JavaScript is the world's most popular programming language. It is the language for HTML and PHP. A function is a block of code that will be executed. The function can be called directly when an event occurs (like when a user clicks a button), and it can be called from "anywhere" by JavaScript code.
Syntax
A function is written as a code block inside curly { } braces.
function functionname() { some code to be executed } |
Function calling with arguments
When you call a function, you can pass values to it. These values are called arguments or parameters.
These arguments can be used inside the function.
You can pass many arguments as you like, separated by commas (,).
Functionname(argument1,argument2) |
Declare the arguments, as variables, when you declare the function.
Access a JavaScript variable from HTML
<--Javascript file with HTML-->
<html>
<head>
<script type="text/javascript">
function myday() {
var d = new Date();
var weekday = new Array(7);
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
var x = document.getElementById("ram");
x.innerHTML = weekday[d.getDay()];
}
function showDate() {
var today = new Date()
var d1 = new Date("October 13,1975 11:13:00");
var x = document.getElementById("ram"); x.innerHTML = [d1.getDate()];
}
function myFunction() {
var month = new Array();
month[0] = "January";
month[1] = "February";
month[2] = "March";
month[3] = "April";
month[4] = "May";
month[5] = "June";
month[6] = "July";
month[7] = "August";
month[8] = "September";
month[9] = "October";
month[10] = "November";
month[11] = "December";
var d = new Date();
var x = document.getElementById("ram");
x.innerHTML = month[d.getMonth()];
}
function displayyear() {
var d = new Date();
var x = document.getElementById("ram");
x.innerHTML = d.getFullYear();
}
</script>
</head>
<body>
<div align="center">
<table border="2" height="20%" width="20%" bgcolor="#FDF2C8">
<tr>
<th><h1><font color="#DC8347">How to use JavaScript</h1></th>
<p id="ram"><b>Display on here</b></p>
<p id="P1"></p>
<p id="P2"></p>
<p id="P3">.</p>
</tr></table>
<button onClick="myday()">Day</button>
<button type="button" onClick="showDate()">Date</button>
<button onClick="myFunction()">Month</button>
<button onClick="displayyear()">Year</button>
</body>
</html>
Output