Showing posts with label Javascript. Show all posts

Javascript supports two types of comments. Double-slashes (//) tell javascript to ignore everything to the end of the line. You will see them used most often to describe what is happening on a particular line.

[code type="JavaScript"]
var x=5; // Everything from the // to end of line is ignored(*)
var thingamajig=123.45; // 2 times the price of a whatsit.
[/code]

Block quotes begin a comment block with a slash-asterisk (/*) and Javascript will ignore everything from the start of the comment block until it encounters an asterisk-slash (*/). Block quotes are useful for temporally disabling large areas of code, or describing the purpose of a function, or detailing the purpose and providing credits for the script itself.

[code type="JavaScript"]
function whirlymajig(jabberwocky) {
/* Here we take the jabberwocky and insert it in the gire-gimble,
taking great care to observe the ipsum lorum! For bor-rath-outgrabe!
We really should patent this! */
return (jabberwocky*2);
}

[/code]

You should note that while comments are useful for maintaining the code, they are a liability itself in Javascript since they will be transmitted along with the code to each and every page load, which can create substantial bandwidth penalties and increase the load time of your page for users.

Javascript events :


As you can tell from the input examples, Javascript is an event driven language which means
your scripts react to events you set up. Your code isn't running all the time, it simply waits until
an event starts something up! Going into all the Javascript events is beyond the scope of this
document but here's a short-list of common events to get you started.

Event :           onAbort
Description:   An image failed to load.
Event :           onBeforeUnload
Description:   The user is navigating away from a page
Event :            onBlur
Description:  A form field lost the focus (User moved to another field)
Event :            onChange
Description:  The contents of a field has changed.
Event :            onClick
Description:  User clicked on this item.
Event :            onDblClick
Description:  User double-clicked on this item.
Event :            onError
Description:  An error occurred while loading an image.
Event :           onFocus 
Description: User just moved into this form element
Event :           onKey
Description: Down A key was pressed
Event :           onKeyPress
Description:  A key was pressed OR released.
Event :          onKeyUp
Description:  A key was released.
Event :            onLoad
Description:  This object (iframe, image, script) finished loading.
Event :          onMouseDown
Description:  A mouse button was pressed.
Event :            onMouseMove
Description:  The mouse moved.
Event :             onMouseOut
Description:   A mouse moved off of this element.
Event :          onMouseOver 
Description:  The mouse moved over this element.
Event :            onMouseUp
Description:  The mouse button was released.
Event :           onReset
Description:  A form reset button was pressed.
Event :           onResize
Description:  The window or frame was resized.
Event :            onSelect
Description:  Text has been selected.
Event :            onSubmit
Description:   A form's Submit button has been pressed.
Event :            onUnload
Description:  The user is navigating away from a page. 


These events can be attached to most any HTML tag or form element. Of them all onClick will probably be what you end up using most often.

Input (User Input) :

Clicks are powerful and easy and you can add an onClick event to pretty much any HTML element, but sometimes you need to be able to ask for input from the user and process it. For that you'll need a basic form element and a button.

 [code type="JavaScript"]
<input id='userInput' size=60>
<button onClick='userSubmit()'>Submit</button>
<BR>
<P><div id='result'></div>
[/code]


Here we create an input field and give it a name of userInput. Then we create a HTML button with an onClick event that will call the function userSubmit(). These are all standard HTML form elements but they're not bound by a <form> tag since we're not going to be submitting this information to a server. Instead, when the user clicks the submit button, the onClick event will call the userSubmit() function.

[code type="JavaScript"]
<script type='text/javascript'>
function userSubmit() {
var UI=document.getElementById('userInput').value;
document.getElementById('result').innerHTML='You typed: '+UI;
}
</script>
[/code]


Here we create a variable called UI which looks up the input field userInput. This lookup is exactly the same as when we looked up our feedback division in the previous example. Since the input field has data, we ask for its value and place that value in our UI variable. The next line looks up the result division and puts our output there. In this case the output will be "You Typed: " followed by whatever the user had typed into the input field.

We don't actually need to have a submit button. If you'd like to process the user input as the user types then simply attach an onKeyup event to the input field as such

[code type="JavaScript"]
<input id='userInput' onKeyUp="userSubmit()" size=60>
<BR>
<P><div id='result'></div>
[/code]

There's no need to modify the userSubmit() function. Now whenever a user presses a key while the userInput box has the focus, for each keypress, userSubmit() will be called, the value of the input box retrieved, and the result division updated.

If everything in HTML is a box and every box can be given a name, then every box can be given
an event as well and one of those events we can look for is "onClick".


[code type="JavaScript"]
<html>
<head>
</head>
<body>
<div id='feedback' onClick='goodbye()'>
Users without Javascript see this.</div>
<script type='text/javascript'>
document.getElementById('feedback').innerHTML='Hello World!';
function goodbye()
{document.getElementById('feedback').innerHTML='Goodbye World!';
}
</script>
</body>
</html>
[/code]



Here we added an "onClick" event to our feedback division which tells it to execute a function called goodbye() when the user clicks on the division. A function is nothing more than a named block of code. In this example goodbye does the exact same thing as our hello world example, it's just named and inserts 'Goodbye World!' instead of 'Hello World!'.

In this example is that we provided some text for people without Javascript to see. As the page loads it will place "Users without Javascript will see this." in the division. If the browser has Javascript, and it's enabled then that text will be immediately overwritten by the first line in the script which looks up the division and inserts "Hello World!", overwriting our initial message. This happens so fast that the process is invisible to the user, they see only the result, not the process. The goodbye() function is not executed until it's explicitly called and that only happens when the user clicks on the division.

The getElementById method is the most powerful and the most complex (but don't worry, it's really easy!). Everything on a web page resides in a box. A paragraph (<P>) is a box. When you mark something as bold you create a little box around that text that will contain bold text. You can give each and every box in HTML a unique identifier (an ID), and Javascript can find boxes you have labeled and let you manipulate them.

[code type="HTML"]<html>
<head>
</head>
<body>
<div id="feedback">
</div>
<script type="text/javascript">
document.getElementById('feedback').innerHTML='Hello World!';
</script>
</body>
</html>[/code]

The page is a little bigger now but it's a lot more powerful and scalable than the other two. Here we defined a division <div> and named it "feedback". That HTML has a name now, it is unique and that means we can use Javascript to find that block, and modify it. We do exactly this in the script below the division! The left part of the statement says on this web page (document) find a block we've named "feedback" ( getElementById('feedback') ), and change its HTML (innerHTML) to be 'Hello World!'. We can change the contents of 'feedback' at any time, even after the page has finished loading (which document.writeln can't do), and without annoying the user with a bunch of pop-up alert boxes (which alert can't do!). It should be mentioned that innerHTML is not a published standard. The standards provide ways to do exactly what we did in our example above. That mentioned, innerHTML is supported by every major Browser and in addition innerHTML works faster, and is easier to use and maintain. It's, therefore, not surprising that the vast majority of web pages use innerHTML over the official standards. While we used "Hello World!" as our first example, its important to note that, with the exception of <script> and <style>, you can use full-blown HTML. Which means instead of just Hello World we could do something like this…

[code type="JavaScript"]
<html>
<head>
</head>
<body>
<div id='feedback'>
</div>
<script type='text/javascript'>
document.getElementById('feedback').innerHTML='<P>
<font color=red>Hello World!</font>';
</script>
</body>
</html>[/code]

In this example, innerHTML will process your string and basically redraw the web page with the new content. This is a VERY powerful and easy to use concept. It means you can basically take an empty HTML element (which our feedback division is) and suddenly expand it out with as much HTML content as you'd like.

The browser alert box:

While these are incredibly useful for debugging (and learning the language), they are a horrible way to communicate with the user. Alert boxes will stop your scripts from running until the user clicks the OK button, and it has all the charm and grace of all those pop-up windows everyone spent so many years trying to get rid of!


[code type="JavaScript"]<html>
<head>
</head>
<body>
<script type="text/javascript">
alert('Hello World!');
</script>
</body>
</html>[/code]

The document.writeln(string) command.


This can be used while the page is being constructed. After the page has finished loading a new
document.writeln(string) command will delete the page in most browsers, so use this only while the page is loading. Here's how a simple web-page will look...


[code type="JavaScript"]<html>
<head>
</head>
<body>
<script type="text/javascript">
document.writeln('Hello World!');
</script>
</body>
</html>[/code]


As the page is loading, Javascript will encounter this script and it will output "Hello World!" exactly where the script block appears on the page. The problem with writeln is that if you use this method after the page has loaded the browser will destroy the page and start constructing a new one. For the most part, document.writeln is useful only when teaching yourself the language. Dynamic content during page load is better served by the server-side scripting languages. That said, document.writeln is very useful in pre-processing forms before they're sent to the server -- you can basically create a new web-page on the fly without the need to contact the server.

External Javascript

External Javascript is where things get interesting. Any time you have a block of code which you will want to use on several different web pages you should place that block in an external Java script file. The clock on the upper right-hand corner of this page is a good example. The clock appears on almost every page on this site and so it is included in my "common.js" file. Every web-page on the site will load this file and so the clock is available to all of my web-pages.

There's nothing fancy about an external Js file. All it is, is a text file where you've put all
your Javascript. Basically everything that would ordinarily go between the <script> tags can go
in your external file. Note that between was stressed, you can not have the <script> </script> tags themselves in your external file or you will get errors.

[code type="JavaScript"]
<script type='text/javascript' src='common.js'>
</script>
[/code]

The biggest advantage to having an external Javascript file is that once the file has been loaded,
the script will hang around the browser's cache which means if the Javascript is loaded on one
page then it's almost a sure thing that the next page on the site the user visits will be able to load the file from the browser's cache instead of having to reload it over the Internet (This is an
incredibly fast and speedy process).

Including an external file is basically the same as doing an in-line script, the only difference is
that you specify a filename, and there's no actual code between <script> and </script>..

When the browser encounters this block it will load common.js, evaluate it, and execute it. Like
in-line scripts above you can place this block anywhere you need the script to be and like in-line
scripts you should place these as close to the bottom of the web-page as you can get away with.
The only difference between in-line Javascript blocks and external Javascript blocks is that an
external Javascript block will pause to load the external file. If you discount that one thing,
there's no procedural difference between the two!

Definition of In-Line Javascript

To define a Javascript block in your web page, simply use the following block of HTML.

[code type="JavaScript"]



[/code]

You can place these script blocks anywhere on the page that you wish, there are some rules and
conventions however.

If you are generating dynamic content as the page loads you will want the
script blocks to appear where you want their output to be. For instance, if I wanted to say "Hello World!" I would want my script block to appear in the <body> area of my web page and not in the <head> section.

Unless your scripts are generating output as the page loads, good practice says that you should
place your scripts at the very bottom of your HTML. The reason for this is that each time the
browser encounters a <script> tag it has to pause, compile the script, execute the script, then
continue on generating the page. This takes time so if you can get away with it, make sure the
browser hits your scripts at the end of the page instead of the start.

Javascript tutorial - learn javascript :

Javascript is a interpreted language with a C like syntax. Whereas most people brush the js language off as nothing more than a browser scripting language, it literally supports many advanced concepts which include object oriented programing, recursion, lambda, and closures. It's really a very approachable language for the learner that quickly scales to be as powerful a tool as your skills allow.

To dive into Java script all you need is a simple text editor and a browser. In windows, you can use notepad under your accessories and Linux and mac users have a similar editor. Simply create a blank HTML page for example …

[code type="HTML"]
<html>
<head>
<title>Learning Javascript</title>
</head>
<body>
<p>Hello World!
</body>
</html>
[/code]

Save the file then open in your internet browser you just created to see the results .Javascript code is interpreted so any changes you make to this file will show up straight away in the browser the moment you hit the reload button.

TECH SHARPENER

.
Powered by Blogger.