Where To – JavaScript Basics

<script> Tag : JavaScript code must be located between opening and closing script tags ; <script> and </script> tags.

<!DOCTYPE html>
 <html>
 <body>

<h1>JavaScript Basics</h1>

<p id="ex"></p>

<script>
 document.getElementById("ex").innerHTML = "Hello World! This Is My First JavaScript";
 </script>

</body>
 </html>

Output :

 

 

 

Block of JavaScript code that can be executed when “called” is a JS Function and when user clicks a button an Event is occured and function can be called.

JS in HTML<head> section:

JavaScript function is kept in HTML page’s <head> section.When a button is clicked this function is called.

<!DOCTYPE html>
 <html>
 <head>
 <script>
 function myFunction() {
 document.getElementById("ex").innerHTML = "Projects, Tutorials & More!";
 }
 </script>
 </head>

<body>
 <h1>JS in Head Section</h1>
 <p id="ex">Code Projects</p>
 <button type="button" onclick="myFunction()">Try It!</button>

</body>
 </html>

Output :

 

 

 

after clicking the button FUNCTION is called

 

 

 

 

JS in HTML<body> section :

JavaScript function is kept in HTML page’s <body> section.When a button is clicked this function is called.

<!DOCTYPE html>
 <html>
 <body>

<h1>JS in Body Section</h1>
 <p id="ex">Code Projects</p>
 <button type="button" onclick="myFunction()">Try it!</button>

<script>
 function myFunction() {
 document.getElementById("ex").innerHTML = "Projects, Tutorials & More";
 }
 </script>

</body>
 </html>

Output :

 

 

 

after clicking the button FUNCTION is called

 

 

 

 

External JS Files :

( script.js )

function myFunction() {
 document.getElementById("ex").innerHTML = "Projects, Tutorials & More";
 }

JavaScript is used external when the same code is used in many different pages. JavaScript files have ( .js ) extension.

Insert name of script file in src (source) attribute of a <script> tag to use External JS:

Check this out!

<!DOCTYPE html>
 <html>
 <body>

<h1>External JavaScript</h1>
<p id="ex">Code Projects</p>
<button type="button" onclick="myFunction()">Try it</button>

<p> <i> NOTE :myFunction() is stored in an external file named "scripts.js" </i> </p>

<script src="script.js"></script>

</body>
 </html>

Output :

 

 

 

 

Function is called after clicking the button (by EXTERNAL JS)

 

 

 

 

 

Leave a Reply

avatar
  Subscribe  
Notify of