First of all we see a normal heading without any java script codes.
<html>
<body>
<h1>This Is A Normal Heading</h1>
</body>
</html>
If you see the out put of the above HTML code in a browser, you will see the following.
To use java script in HTML page, you should know where to place the <script> tag.You place your Java Scripts inside the <body> or <head> section.You can use any number of java scripts in an HTML document. If you want to you can place Java Script in both the <head> and <body>. As a best practice you can place Java Scripts in bottom of the body. This will reduce the time that need to display the page.
Now lets add a Java Script code to change the heading. In order to do that first of all we have to give ID to our heading. Then we can identify the heading using the unique id. Following HTML code will demonstrate to use java script.
<html>
<body>
<h1 id="myHeading">This Is A Normal Heading</h1>
<script>
document.getElementById("myHeading").innerHTML = "My First Java Scipt";
</script>
</body>
</html>
Now lets create a function to do this.following code will initially generate a heading with a text "This Is A Normal Heading" and a button.When button clicked it should call a function to change the text of the heading.Following code will do this task for you.
<html>
<body>
<h1 id="myHeading">This Is A Normal Heading</h1>
<button type="button" onclick="changeHeading()">Change Heading</button>
<script type="text/javascript">
function changeHeading(){
document.getElementById("myHeading").innerHTML = "My First Java Scipt";
}
</script>
</body>
</html>
Now lets try another thing. Rather than placing the java script code below the <body> section, place it inside the <head> section.
<html>
<head>
<script type="text/javascript">
function changeHeading(){
document.getElementById("myHeading").innerHTML = "My First Java Scipt";
}
</script>
</head>
<body>
<h1 id="myHeading">This Is A Normal Heading</h1>
<button type="button" onclick="changeHeading()">Change Heading</button>
</body>
</html>
When you have a huge java script code,its better to keep your java script codes in a separate file(.js). Now will try to place the above java script in a separate java script file.
ChangeHeader.js
function changeHeading(){
document.getElementById("myHeading").innerHTML = "My First Java Scipt";
}
<html>
<head>
<script src="ChangeHeader.js"></script>
</head>
<body>
<h1 id="myHeading">This Is A Normal Heading</h1>
<button type="button" onclick="changeHeading()">Change Heading</button>
</body>
</html>
<html>
<body>
<h1 id="myHeading">This Is A Normal Heading</h1>
<button type="button" onclick="changeHeading()">Change Heading</button>
<script src="ChangeHeader.js"></script>
</body>
</html>
No comments:
Post a Comment