Thứ Tư, 24 tháng 2, 2016

Types of calling a function while click in javascript

     In javascript we can call a function while clicking html elements in three types, they are define in following example.

1) onclick
2) object.onclick
3) addEventListener


1) onclick:
     This is type is define inside the html tag. When you want to call a function in while clicking you can use the onclick attribute inside the html elements.

Syntax

<element onclick="script or function calling">


Example

<script>

 function cl_fun()

{

  alert("Function Called");

}

</script>



 <input type="button" onclick="cl_fun();" value="Click Here">


2) object.onclick
     In this method we are call a function using html elements id.

Syntax

var obj=document.getElementById("element_id");

obj.onclick=function(){/*script here*/};



Example

<script>

 var obj=document.getElementById("btnid");

 obj.onclick=function(){alert("Function Called");};



or

 var obj=document.getElementById("btnid");

 obj.onclick=function_name;

</script>



  <input type="button" id="btnid" value="Click Here">


3) addEventListener
     addEventListener also define such as object.onclick, the example is shown below.

Syntax:

 var obj=document.getElementById("element_id");

obj.addEventListener("click",function(){/*script here*/},useCapture);



 or

 var obj=document.getElementById("element_id");

 obj.addEventListener("click",function_name,useCapture);


addEventListener false why?
       The third parameter is If true, useCapture indicates that the user wishes to initiate capture. After initiating capture, all events of the specified type will be dispatched to the registered listener before being dispatched to any EventTargets beneath it in the DOM tree. Events which are bubbling upward through the tree will not trigger a listener designated to use capture. See DOM Level 3 Events for a detailed explanation.

Example

<script>

 var obj=document.getElementById("btnid");

 obj.addEventListener("click",function(){alert("Function Called"),false};

</script>



 <input type="button" id="btnid" value="Click Here">


Example Program:- (Editor)


Editor is Loading...

Advertisement




Tag:
click function using javascrip in allinworld99, click event in javascript allinworld99

0 nhận xét:

Đăng nhận xét