Embedding JavaScript in HTML

The <script> is to assist the browser in recognizing lines of code in an HTML document as belonging to a script, you surround lines of script code with a
<script>...</script> tag set. tag. Script with src,
<script src="my-script.js" type="text/javascript"></script>
The purpose is to define functions, objects, and variables. Functions will later be triggered by buttons, other user events, inline script tags with body content, etc. script with body content

<script type="text/javascript">JavaScript code</script>

Purpose is to define functions, objects, and variables. To directly invoke code that will run as page loads, to output HTML content built by JavaScript Don't use this approach for defining functions or for doing things that could be done in external files. Slower (no browser caching) and less reusable.

Learn By Example-1:
//Example (phish.js)
function getMessage() {
var amount = Math.round(Math.random() * 100000);
var message =
"You won $" + amount + "!\n" +
"To collect your winnings, send your credit card\n" +
"and bank details to oil-minister@phisher.com.";
return(message);
}
function showWinnings1() {
alert(getMessage());//"alert" pops up dialog box
}
function showWinnings2() {
document.write("<h1><blink>" + getMessage() +
"</blink></h1>");
//"document.write" inserts text into page at current location.

//Example (loading-scripts.html)
<!DOCTYPE ...><html xmlns="http://www.w3.org/1999/xhtml">
<head><title>Loading Scripts</title>
...
<script src="./scripts/phish.js"//Loads script from previous page
type="text/javascript"></script>
</head>
<body>
...
<input type="button" value="How Much Did You Win?"
onclick='showWinnings1()'/>
//Calls showWinnings1 when user presses
//button. Puts result in dialog box.
...
<script type="text/javascript">showWinnings2()</script>
//Calls showWinnings2 when page is loaded in
//browser. Puts result at this location in page.
...
</body></html>

0 comments:

Post a Comment

 

About Me

It's Me!Hi, I'm Moinuddin. I'm a Software Engineer at WIPRO working on Microsoft .NET Technology. I'm interested in a wide range of technology topics, mainly Microsoft including Windows Azure, WCF, WPF, Silverlight and any other cool technology that catches the eye.

Site Info

ProjectCSharp.com is mainly about demonstrating real time examples in different technologies like ASP.NET, WCF, WPF, Silverlight, Azure etc..,

Followers

Help Links

Project CSharp (C#) Copyright © 2011. All Rights Reserved.