...

View Full Version : Code For Writing OnClick In JS Files..???



mantix
03-24-2009, 10:04 AM
Hai Guys,

ANyone Can Give Me Sample Code For OnClick Operation In JS File..



Thanks:

Philip M
03-24-2009, 10:22 AM
Event handlers such as onclick are not part of Javascript but are part of HTML. And you cannot have any HTML in a script or .js file.


Customer in UK travel agent shop: - "What month is it now in Australia?"

freedom_razor
03-24-2009, 01:22 PM
Well, they are a part of Javascript too. Here's the example Javascript file:
test.js

function example(){alert('Clicked!')}
function inthejsfile(){
for(i=0;i<document.links.length;i++){
document.links[i].onclick=example;
}
}
window.onload=inthejsfile;

and example HTML file:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title></title>
<script type="text/javascript" src="test.js"></script>
</head>
<body>
<a href="">Example link 1</a>
<a href="">Example link 2</a>
<a href="">Example link 3</a>
</body>
</html>

Functions in .js file attach simple event handler to all links in the document, this happens after the document has been loaded.

VIPStephan
03-24-2009, 01:36 PM
In fact, in order to have unobtrusive JavaScript (http://en.wikipedia.org/wiki/Unobtrusive_JavaScript) (which is part of the progressive enhancement (http://en.wikipedia.org/wiki/Progressive_enhancement) approach) you must write such events in an external JavaScript, not in the HTML.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum