Strona główna HTML i javascript C++ Hardware HTML i javascript Java Software SQL

Javascript - registration events on page.

Dodano: 2012-01-27

Together with the developments the language javascript and of new standards of encoding page www, evolved the ways of registration events on page.

At the beginning of the javascript to create reaction on page, web developer had to add attribute to tag and add function as parameters, which is performed after the occurrence of a particular event. That method adding reaction to events has name inline. Disadvantage of this solution is the ability to only adding one function.

After adding lot of attributes to tag, code page was less readable. Samples of use inline method:

<html>
<head>
<script type="text/javascript">

function cl(){
	window.alert("klik ;)");
}

</script>
</head>

<body>
<input type="button" value="klik" onclick="cl();">
</body>
</html>

Together with the creation of standards of coding www, has been semirechye three elements of page:

  • content: text, picture, movie, sound etc.
  • structure: used tags, to specification which elements is
  • presentation: CSS, definition visualization of elements,
  • script: my elements ;)

After creating standard, web developer can register an events by object.onlcick = doSomthing.

<html>
<head>
<script type="text/javascript">

function cl(){
	window.alert("klik ;)");
}

</script>
</head>

<body>
<input id="KLIK" type="button" value="klik" >

<script type="text/javascript">
	document.getElementById("KLIK").onclick = cl;	
</script>
</body>
</html>
Newest standards, allow you to add many reaction to one event. To registration events use attachEvent([event], [function]) in Internet Explorer, and addEventListener([event], [function], false) in case Opera, Firefox, Chrome. Below example how to add events in browsers Internet Explorer, Firefox, Opera, Chrome.

<html>
<head>
<script type="text/javascript">

function addEventListner(ev, fun, objId){
	var obj = document.getElementById(objId);
	if (obj.addEventListener) {
 		obj.addEventListener(ev, fun, false);
	 } else if (obj.attachEvent)  { //ie
		obj.attachEvent("on"+ev, fun);
	 } 
}

function cl01(){
	window.alert("klik 01");
}

function cl02(){
	window.alert("klik 02");
}

</script>
</head>

<body>
<input id="KLIK" type="button" value="klik" >

<script type="text/javascript">
	addEventListner("click", cl01, "KLIK");
	addEventListner("click", cl02, "KLIK");
</script>
</body>
</html>

Standards HTML wikipedia
Specification javascript ECMA-262, 5.1 Edition