Showing posts with label JavaScript. Show all posts

JavaScript Part-12 Closures

A closure in JavaScript is an inner function that has access to its outer function's scope, even after the outer function has returned control. A closure makes the variables of the inner function private. A

Simple example of a closure is shown below:

var count = (function () {
var _counter = 0;
return function () {return _counter += 1;}
})();

count();
count();
count();

// the counter is now 3



The variable count is assigned an outer function. The outer function runs only once, which sets the counter to zero and returns an inner function. The _counter variable can be accessed only by the inner function, which makes it behave like a private variable.


Saturday, 10 March 2018
Posted by Sudhir Chekuri

JavaScript Part-11 IIFE ( Immediately invoked function expressions )

IIFE ( Immediately invoked function expression ) is a function that's executed as soon as it's created. It is a self invoking anonymous function. It has no connection with any events or asynchronous execution.

Syntax:

( function( ) {
     // Code goes here
     // ...
    } )( );

Explanation:

1.  ( function( ) {
     // Code goes here
     // ...
    } )( );

All the code inside the function will be converted into an expression.

2.  ( function( ) {
     // Code goes here
     // ...
    } )( );

The second pair of parentheses calls the function resulting from the expression.

Its most common usage is to limit the scope of a variable made via var or to encapsulate context to avoid name collisions.


Posted by Sudhir Chekuri

JavaScript Part-10 Event handlers


Event handlers are used to execute a function based on the action performed by the user like onclick, onload, onmouseover etc

In the below example 3 buttons are available on the web page - Touch me 1, Touch me 2 and Touch me 3
onClick event is fired when user clicks on each button.
Alert boxes are displayed on user button click.
Touch me 1 - Alert button code is written in html tag.
Touch me 2 - Function named "first" is called on onClick.
Touch me 3 - Function named "second" is called by passing a parameter named "a".

Example code for onClick event handler

<!DOCTYPE html>
<html>

  <head>
 
   <script type="text/javascript">
   
      function first()
      {
     
        alert('Without parameter');
      }
      function second(a)
      {
     
         alert('With parameter '+a);
      }
   
   
    </script>
 
  </head>

  <body>
    <form>
      <!--alert box code in click event-->
      <input type="button" value="Touch me 1" onClick="alert('Hello')" />
      <!--Function called in click event-->
      <input type="button" value="Touch me 2" onClick="first()" />
      <!--Function with parameter called in click event-->
      <input type="button" value="Touch me 3" onClick="second('Hello')" />
    </form>
 
  </body>

</html>

Output



Posted by Sudhir Chekuri

JavaScript Part-9 Calling function in a function

Two functions named as first and second are created then i called both functions in other function called start.

On the page load "start function" will be called when script is executed. Start function will call "first function" and then "second function".

Javascript example code for calling function in a function:

<!DOCTYPE html>
<html>

  <head>
 
   <script type="text/javascript">
      function First()
      {
        document.write("I am first function ")
      }
      function Second()
      {
        document.write("I am second function")
      }
      function start(){
        First();
        Second();
      }
      start();
    </script>
 
  </head>

  <body>
   
    <h1>Hello World!</h1>
  </body>

</html>

Output:

I am first function I am second function

Hello World!



Posted by Sudhir Chekuri

JavaScript Part-8 Required field validation using js code

Javascript example code to add required field validation for html input textbox

<!DOCTYPE html>
<html>
<head>
<script>
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
  {
  alert("First name must be filled out");
  return false;
  }
}
</script>
</head>

<body>
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>
</html>



Sunday, 27 October 2013
Posted by Sudhir Chekuri

JavaScript Part-7 Sending input parameters for js function

In this example when user click on the button two input parameters are sent to the js function to print them in alert box

JS code to send input parameters for function


<!DOCTYPE html>
<html>
<body>
    <p>Click the button to call a function with arguments</p>
    <button onclick="myFunction('Hello','World')">Try it</button>
    <script>
        function myFunction(name, job) {
            alert("Welcome " + name + ", the " + job);
        }
    </script>
</body>
</html>




Posted by Sudhir Chekuri

Javascript Part-6 changing css class using js code if condition

In this example i wrote two css classes cssclass1 and cssclass2.
when page is loaded cssclass1 styles is applied to the div1 tag and when user click on the button cssclass2 is applied to div tag using javascript.

js code to change css class of div tag


<!DOCTYPE html>
<html>
<head>
    <style type="text/css" >
        .cssclass1
        {
        width:200px;
        height:200px;
        background-color:yellow;
        }

        .cssclass2
        {
        width:200px;
        height:200px;
        background-color:green;
        }
    </style>
<script language="javascript"> 
    function f1() {
        var css = document.getElementById("div1").className;
        if (css == "cssclass1") {
            document.getElementById("div1").className = "cssclass2";
        } else { document.getElementById("div1").className = "cssclass1"; }
    }
</script>
</head>

<body>
<div id="div1" class="cssclass2" >Text inside div tag</div>
<input type="button" value="Submit" onclick="f1()">
</body>

</html>


Posted by Sudhir Chekuri

Javascript Part-5 changing background color style property using js code

Javascript code to change the background color style of div tag based on the color selected from dropdown by the user

<html>
<head>
<script>
function f1()
{
var x= document.getElementById('colorpicker').value;
document.getElementById('colormsg').style.background= x;
}
</script>
</head>
<body>
<div id='colormsg' font-size="100px";width="100";height="180";padding="5px">choose a background color</div>
<select id='colorpicker' onclick='f1()'/>
<option value="transparent">None</option>
<option value="Yellow">yellow</option>
<option value="Cyan">cyan</option>
<option value="pink">Pink</option>
</body>

</html>





Posted by Sudhir Chekuri

Javascript Part-3 inner html property to create html

In the below example onkeyup event is fired after every release of keyboard key.
placeholder property is used to display a watermark message inside textbox.
innerHTML is the property used in js code to add h1 tag inside paragraph tag.


Js code to print text entered in textbox as heading in paragraph


<html>
<head>
    <script type="text/javascript">
        function showMsg() {
            var userInput = document.getElementById('userInput').value;
            document.getElementById('userMsg').innerHTML = "<h1>"+userInput+"</h1>";
        }
    </script>
</head>
<body>
    <input type="text" maxlength="40" id="userInput" onkeyup="showMsg()" placeholder="Enter text here..." />
    <p id="userMsg"></p>
</body>
</html>




Posted by Sudhir Chekuri

Javascript Part-2 using variables , comments

Variables are used to hold the data retrieved from input controls.

In the below example a textbox and a button is displayed on the output screen. The text entered in the textbox is displayed in an alertbox when user clicks on the button.
In the below example txt1 is the id given to a textbox which is used to retreive its value using js code.
document.getElementById is used to find an item with id as txt1 in the html document.

Javascript code to display entered text in an alertbox

<html>
<head>
<script language="javascript">
function f1()
{
var a=document.getElementById("txt1").value;
alert(a);
}
</script>
</head>
<body>
<input type="text" id="txt1"/>
<input type="button" value="click me" onclick="f1()"/>
</body>
</html>



In the below example two textboxes and a button is displayed on the output screen. when user clicks on the button the added value of the two textboxes is displayed in an alert box.
parseInt is the function used to convert a value inside a variable into numeric type to perform arthimetic operations.

javascript code to add two numbers entered in two textboxes

<HTML>
<head>
<script language="javascript">
function f1()
{
var a=document.getElementById("txt1").value;
var b=document.getElementById("txt2").value;
var c=parseInt( a)+parseInt(b);
alert(c);
}
</script>

</head>
<body>
<input type="text" id="txt1"/>
<input type="text" id="txt2"/>
<button id="btn1" onclick="f1()" >
Click me
</button>
</body>
</html>


Comments

 //single line comments goes here
/* Multi line 
    comments in javascript
  */

Global variable: Variable that is created ouside the body of the function.
Local variable: Variable that is created inside the body of the function.

In the below example global variable "word" is created outside the function which can be called within and outside the function named "first".

Global variable example code:


<!DOCTYPE html>
<html>
  <head>
   
   <script type="text/javascript">
      var word="ABCD ";
      function first()
      {
     
        document.write("inside: "+word);
      }
   
       document.write("outside: "+word);
      first();
    </script>
   
  </head>
  <body>
  </body>
</html>

Output:

outside: ABCD inside: ABCD
------------------------

In the below example local variable "alphabet" is created inside the function which can be called within  the function named "first" only.

<!DOCTYPE html>
<html>

  <head>
   
   <script type="text/javascript">
   
      function first()
      {
        var alphabet="C ";
        document.write("inside: "+alphabet);
      }
   
      first();
    </script>
   
  </head>

  <body>
   
  </body>

</html>

Output:

inside: C
Posted by Sudhir Chekuri

Javascript Part-1 What is Javascript?

What is Javascript?

It is a light weight client side scripting language.
You can write javascript code in html page to convert static web page to dynamic page.
It is a case sensitive language ie., you cannot use lowercase letters incase of uppercase letters.
It is recommended to write javascript in head tag.
Javascript functions should be written inside <script> and </script>.
It is executed line by line by interpreter.
You can write javascript in external javascript file with .js as extension. You can call javascript functions written in external js file by adding the below tag in the html page.

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

Using javascript we can change the properties of html elements, create html tags in runtime, change css styles in runtime.

Example javascript code in html file

<html>
<head>
<script language="javascript">
function f1()
{
alert('hi');
}
</script>
</head>
<body>
<input type="button" value="click me" onclick="f1()"/>
</body>

</html>

In the above code a button is created using html input button tag. It Clickme is the text displayed on the button. onclick is the event which calls javascript function f1 when user clicks on the button.
f1 function is written inside the script tag. alert box with hi message is displayed when user click on the button.

Example to call javascript function written in external js file

code in html file
<html>
<head>
<script src="external.js">
</script>
</head>
<body>
<input type="button" value="click me" onclick="f1()"/>
</body>

</html>

code in external.js file

function f1()
{
alert('hi');

}


Saturday, 26 October 2013
Posted by Sudhir Chekuri

Javascript code to display text entered by user in alert box

I used two html inputs in this example. They are textbox and a button.
id for textbox is txt1 and it is used to get its value using javascript code.
value entered in texbox txt1 is saved in variable a and then it is displayed in alert box using function f1.
onclick event is fired when user click on a button to execute javascript code written inside function f1.

HTML and Javascript code to display text entered by user in alert box

<html>
<head>
    <script type="text/javascript" >
        function f1()
        {
            var a = document.getElementById("txt1").value;
            alert(a);
        }
    </script>
</head>

<body>
    <input type="text" id="txt1"/>
    <br/>
    <input type="button" value="Click" onclick="f1()"/>
</body>
</html>
Thursday, 17 October 2013
Posted by Sudhir Chekuri

Javascript Part-4 Changing HTML Image using Javascript code

I displayed an image using img tag on a html page. src is the attribute used to add source for img tag. My image is placed in a folder named as images so i used the below format.
ImgSideBar is the image id which is used to access the properties of image tag using javascript code.

HTML Code for image tag displaying image

<img id="ImgSideBar" src="images/KrrishSideBar.png" />

Now when the webpage is opened in the browser it will display image named KrrishSideBar in the image control.

No on a button click i want to display other image named as KrrishSideBar2 in the same image control for that i used the below javascript code inside a javascript function which is called using button click event.

Javascript code to change image on button click

function f1()
{
document.getElementById("ImgSideBar").src = "images/Krissh/KrrishSideBar2.png";
}

Example code

<html>
<body>
<script>
function changeImage()
{
element=document.getElementById('myimage')
if (element.src.match("pic1"))
  {
  element.src="pic1.gif";
  }
else
  {
  element.src="pic2.gif";
  }
}
</script>

<img id="myimage" onclick="changeImage()"
src="pic1.gif" width="100" height="180">

<p>Click on image to change</p>

</body>

</html>




Monday, 7 October 2013
Posted by Sudhir Chekuri

Followers

Total Pageviews

Powered by Blogger.

- Copyright © 2013 DevStudent - Metrominimalist - Powered by Blogger - Designed by Johanes Djogan -