Javascript for Beginners

If you are using the internet to access web applications, the applications you are using are made from many languages; javascript is one. Javascript is one of the languages used widespread by web developers. This language helps present the content in a more interactive way to the end-user. In this tutorial, I will cover the basics of this language and then cover some examples that help you understand how javascript works. At the end of this tutorial, you learn the basics of javascript and know how you can use this language. I will cover some examples also as a part of this tutorial.

What is Javascript?
Javascript is an object-oriented scripting language used by web developers. Basically, it is a scripting language that runs and is executed as part of HTML code. As you know, that primary technology for creating web pages is HTML; javascript acts as the supplement to create web pages more interactive and provide a better presentation of information to end-users. If you try to see the source code of web pages, you can found embedded javascript code with big HTML code. The browser interprets javascript, and hence it helps javascript to make it platform-independent.

What is the need for Javascript?
As HTML is the primary language of data presentation on the web, you may ask why javascript is needed? Basically, javascript helps HTML in performing various functions such as:

  • form submission
  • online data validation. e.g., validation of numerals in a phone number field
  • performing mathematical and string calculation
  • decision making based on interactive user response.

Javascript is an Object-oriented language.
As I stated earlier, javascript is an object-oriented language. So, there is a concept of objects, properties, and methods. Javascript allows interaction with the properties and methods with objects that are recognized. An object is a collection of properties and methods which can be viewed, modified, and interacted with. Consider an object; it contains many variables that may call properties and many functions to execute different tasks called methods.

Both these properties and methods are public and private. If methods and properties are public, it can be accessed by other objects. But if they are private, it can be accessed only within the object.
Consider an example of a property that is color. This is one web page property and can be accessed directly by referring to the object and the property by name and then setting its value. e.g., document.bgcolor= "blue";

Object broadly classified into two types:

  • Internal /built-in objects (e.g. window objects)
  • Browser objects (e.g., document objects)

Another example of the use of methods. We use method write(), referred by document object, to write specific string. e.g., document.write("All About Testing");

Javascript can run on both sides: client-side (browser) and server-side (Web Server). But most of the javascript code nowadays runs on the client-side. Javascript must either be a part of the HTML document or referenced as an external file loaded with an HTML document.

Is there any similarity between Javascript and Java?
Most of the people got confused regarding javascript and java. It looks similar in that both contain the java keyword, but basically, both are different languages to serve different purposes.

  • One similarity is both are object-oriented languages.
  • Javascript is interpreted directly by the web browser, and if you want to see source code, you can do it by right-clicking on the web page and by view source code. But java programs need to be first compiled and converted into bytecode and need a java interpreter to execute Java bytecodes.
  • Javascript is a small language used to support HTML for validation, small mathematical calculations, etc. while Java is a full-fledged powerful language and can create a highly complex application. Java is considered as a substitute for powerful languages such as C and C++.

Typical javascript embedded in HTML document:

<html>
 <head>
  <title> sample title </title>
  <script>
        <!--javascript code-->
  </script>
 </head>
<body>
 <script>
        <!--javascript code-->
  </script>
</body>
</html>

Examples:

To create javascript code:

  • open notepad < write script < save it as webpage_name.html.
  • To see the output, right-click on the saved HTML document and open it in a web browser.

Example 1:  Write a new line in the javascript "writeln" method is used.

<html>
 <head>
  <title> sample title </title>
 </head>
<body>
 <script>
      //output specified string and line break
       document.writeln("<h1>Hello Readers</h1>"); 
       document.writeln("<h3>Are you enjoy learning</h3>");
  </script>
</body>
</html>
click here to see output

Example 2: On pressing the "click" button, pop up comes by using alert() method.

<html>
	<body>
 		<script>
              		function respond()
		{
			alert("Welcome");
		}
	        
  		</script>
	<h1> Click on button </h1>
	<form>
		<input type="button" value="click" onclick="respond()">
	</form>
	</body>
</html>
click here to see output

Example 3: To decide on a response to the window, confirm() method is used. In the below example, based on your choice, output will come.

<html>
	<body>
 		<script>
              		function navigate_page()
		{
			var c=confirm("Want to visit my website?");
			if (c==true)
				window.location="https://www.allabouttesting.org";
			else
				window.location="";
		}
	        
  		</script>
	<h1> Click on button </h1>
	<form>
		<input type="button" value="click" onclick="navigate_page()">
	</form>
	</body>
</html>
click here to see output

Example 4: To change the color of the background, "backgroundColor" property is used.

<html>
<head><script>
              		function color_change()
		{
			if (document.body.style.backgroundColor == "#0000ff")
				document.body.style.backgroundColor = "#00ff00";
						else 
                                document.body.style.backgroundColor = "#0000ff";
				
		}
	        
  		</script></head>
	<body>
 		
	<h1> Change the color of the background by javascript </h1>
	<form>
		<input type="button" value="Change color" onclick="color_change()">
	</form>
	</body>
</html>
click here to see output

Example 5: To read input value and verify whether it is correct or not.

<html>
  <head>
    <script>
		function mcq(a)
		{
             /**use this for converting the user input in lower case*/
                 var ans=a.toLowerCase(); 
			if(ans=="yes")
				alert(a+" is correct answer");
			else 	
				alert(a+" is incorrect answer");
		}       
    </script>
  </head>
  <body>		
	<h1> Give the answer of this Question</h1>
	<form id="myform">
                <p><b>Question:</b>Delhi is capital of India?<p>
		<p><b>Answer:</b> <input type="text" name="option" size="7" </p>
                <input type="button" value="Submit" onclick="mcq(option.value)">
	</form>
   </body>
</html>
click here to see output

Example 6: Below example illustrate the use of array and for loop in javascript.

<html>
	<body>
 		<title>List most popular actors:</title>
		<script>
			actor= new Array(3);
			actor[0] = "Salman Khan"
			actor[1] = "Tom Cruise"
			actor[2] = "Aamir Khan"
		</script>
		<script>
			var number = actor.length;
			document.write ("<h2> Best actor </h2>" + "<P>");
			for ( i=0; i < number ; i++)
				document.write ("Rank " +  (i+1) + ": " + actor[i] + "<P>");
		</script>
		
	
	</body>
</html>
click here to see output

Example 7: Illustrate the use of different mouse events in javascript.

<html>
  <head>
    <style>
        .mouse_exp
               {
                height:100px;
                width:400px;
                text-align:center;
                font:bold 40px Verdana;
                background-color:#FF5733;
                padding:80px 20px;
                color:#0B0B0A;
               }
     </style> 
     <script>
          function mouse_hover(event)
                      {
                  //this event called when mouse is over the div.
                     event.innerHTML = "Thank you for coming over me.";
                           event.style.color="#FAFAF3";
                      }

          function mouse_out(event)
                    {
                    //this event called when mouse is out from the div.
                       event.innerHTML = "Cursor is out now.";
                       event.style.color="#F6F908";
                    }
      </script>
   </head>
   <body>
<div class="mouse_exp" onmouseover="mouse_hover(this)" onmouseout="mouse_out(this)">
Mouse Over Example
   </div>
    </body>
</html>
click here to see output

Example 8: Illustrate the use of javascript for animation.

<html>
  <head>
        <style>
            #container
                 {
                   width: 400px;
                   height: 400px;
                   position: relative;
                   background: yellow;
                }
          #circle
              {
               height: 25px;
               width: 25px;
               background-color: #bbb;
               border-radius: 50%;
               position:relative;
             }
       </style>
       <script>
            function objectMove()
                {
                 var elem = document.getElementById("circle");   
                 var pos = 0;
                 var wt=25;
                 var ht=25;
                 var id = setInterval(frame, 50);
            function frame()
               {
                 if (pos == 190)
                     {
                     clearInterval(id);
                     }
                else
                   { 
                   ht=ht+1;
                   wt=wt+1;
                   pos++; 
                   elem.style.top = pos + 'px'; 
                   elem.style.width=wt+'px';
                   elem.style.height=ht+'px';
                   elem.style.left = pos + 'px'; 
                  }
            }
        }
      </script>
   </head>
   <body>
          <p>
          <button onclick="objectMove()">Click Me</button>
         </p> 
        <div id ="container">
              <div id ="circle"></div>
         </div>
    </body>
</html>
click here to see output

Subscribe us to receive more such articles updates in your email.

If you have any questions, feel free to ask in the comments section below. Nothing gives me greater joy than helping my readers!

Disclaimer: This tutorial is for educational purpose only. Individual is solely responsible for any illegal act.

You may also like...

Leave a Reply

Your email address will not be published.