Javascript Basics

Javascript Introduction

What is javascript?

  • JavaScript is a lightweight, interpreted scripting language.
  • Very easy to implement because it is integrated with HTML.
  • Client-side scripting language which is used to interact with the user and make dynamic pages.
  • JavaScript was first known as LiveScript, but Netscape changed its name to JavaScript.
  • Support object-oriented concepts.

How to place javascript code in HTML document?

Javascript code can be placed inside the script tag in head, body or in external file.
Javascript code can be placed inside the <script> tag.
 script language="javascript" type="text/javascript">
   // JavaScript code
</script>

type property

language and type properties are used to specify the scripting langauge.

First Javascript code

<html>
   <body>
      <div$gt;</div>
      <script language="javascript" type="text/javascript">
            document.getElementById('div').innerHTML = "Welcome to Javascript!";
      </script>
   </body>
</html>
Output:
Welcome to Javascript! 
We can place any number of scripts in an HTML document and scripts can be placed in <body>, or in <head>, or in both section of HTML document.

Javascript in head tag

//Javascript in head section

<!DOCTYPE html>
<html>
<head>
<script>
function updateAbstract() {
    document.getElementById("abstract").innerHTML = "Abstract Content.";
}
</script>
</head>
<body>
<p id="abstract">content</p>
<button type="button" onclick="updateAbstract()">Update</button>
</body>
</html>

Javascript in body tag

//Javascript in body section

<!DOCTYPE html>
<html>
<body>
<p id="abstract">content</p>
<button type="button" onclick="updateAbstract()">Update</button>
<script>
function updateAbstract() {
    document.getElementById("abstract").innerHTML = "Abstract Content.";
}
</script>
</body>
</html>

Javascript in External File

We can also place javascript code in external scripts file.
myscripts.js code:
function updateAbstract() {
    document.getElementById("abstract").innerHTML = "Abstract Content.";
}

//HTML code:
<!DOCTYPE html>
<html>
<head>
<script src="myscripts.js" > </script>
</head>
<body>
<p id="abstract">content</p>
<button type="button" onclick="updateAbstract()">Update</button>
</body>
</html>
Ouptut:
//once clicked button, below text appears.

Abstract Content.