Our tutorials have been submitted by our own members and staff over the last four years. They cover a range of design packages and programming languages.
Tutorials are key part of learning new skills, so we not only recommend that you try some, we suggest you experiment with the framework that they give you, don't be scared to wander from the instructions.
Click the categories below to get started!
Alternatively you can pass on your useful tips and advice to others, by creating your own.
Submit a Tutorial
If you like a tutorial, please use the "digg" button below it.
Our tutorials have been submitted by our own members and staff over the last four years. They cover a range of design packages and programming languages.
Tutorials are key part of learning new skills, so we not only recommend that you try some, we suggest you experiment with the framework that they give you, don't be scared to wander from the instructions.
Click the categories below to get started!
Alternatively you can pass on your useful tips and advice to others, by creating your own.
Submit a Tutorial
If you like a tutorial, please use the "digg" button below it.
A variable is a little bit of memory, it'll hold a value defined to it. They're used for accessing later, so you can work with its information. AS1.0 and AS2.0 work with variables in the same fashion, except for one major difference. I'll be sure to point that out later. To create a variable, you'll use the following syntax:
var myString = "Hey";
Notice the "var"? That's announcing the variable. The word following it is the variable name. In the above case, I assigned the value "Hey" to the variable. The ending semi-colon announces the end of the line (The semi-colon is required).
AS2.0 Only:
Variables in AS2.0 have one extra feature. Datatype definition.
var myString:String = "Hey";
Notice the ":String"? That's the Datatype. When you go to type the above in, after inputting the colon, a list will drop with all the Datatypes. Look through it sometime.
Alright, now that you know how to assign variables, I'll introduce you to a method commonly used in Flash. The trace() method.
var myString = "Hello, this is a variable"; trace("The variable's value: " + myString);
Put that into Flash's Action's panel, and press "Ctrl + Enter". You'll notice the output box. That is caused by the trace() method, as it is used to display data. If you haven't already guessed, the value to by outputted is defined inside the parenthesis.
Also, the "+" Operater can be used to combine to entities. In this case, a String and a variable. So, you now know how to create variables and output them. As you continue with Flash, you'll find more and more used for them, this was just a quick intro :)
The music doesnt start automaticly. Find a short but simple loopable .wav file. .wav is recommended but you can use .MP3 or Newgrounds are great places to find music Open flash (obviously)
Make 3 Keyframes if you are going to put a small preloader useless)
Make 2 keyframes if you wont use a preloader
In frame 2 (It's Frame 1 for those that didnt included a preloader.)
Make a button that says PLAY Right click on frame 2 (It's Frame 1 for those that didnt included a preloader.) and select ACTION in the action window, put this exact code:
stop();
Now right click on frame 3 (It's Frame 2 for those that didnt included a preloader.) and select ACTION again Put this exact BIG chunk of code
stop(); if(_global.Behaviors == null)_global.Behaviors = {}; if(_global.Behaviors.Sound == null)_global.Behaviors.Sound = {}; if(typeof this.createEmptyMovieClip == 'undefined'){ this._parent.createEmptyMovieClip('BS_music',new Date().getTime()-(Math.floor((new Date().getTime()) /10000)*10000) ); _global.Behaviors.Sound.music = new Sound(this._parent.BS_music); } else { this.createEmptyMovieClip('_music_',new Date().getTime()-(Math.floor((new Date().getTime()) /10000)*10000) ); _global.Behaviors.Sound.music = new Sound(this.BS_music); } _global.Behaviors.Sound.music.attachSound(\"music\"); if (true) { _global.Behaviors.Sound.music.start(0,50); }
Were it say
.Sound.music.start(0,50);
50 is the number of time the music will loop In the same frame, put a button that say STOP
Now right-click on the new STOP button and choose ACTION Put that exact code in:
on (release) { gotoAndStop(2); _global.Behaviors.Sound.music.stop(); }
Do the same for the PLAY button but this time, put this code in:
on (release) { nextFrame(); }
still there? ok, now the easy part Import your song file-import Go in the Library and right click on your song, select LINKAGE check EXPORT FOR ACTIONSCRIPT you should have 2 checkbox checked In the IDENTIFIER field, type music Thats all! press ok, test your button and it should work fine!
Our tutorials have been submitted by our own members and staff over the last four years. They cover a range of design packages and programming languages.
Tutorials are key part of learning new skills, so we not only recommend that you try some, we suggest you experiment with the framework that they give you, don't be scared to wander from the instructions.
Click the categories below to get started!
Alternatively you can pass on your useful tips and advice to others, by creating your own.
Submit a Tutorial
If you like a tutorial, please use the "digg" button below it.
Definition
The scope of a variale is the rande of which it is defined.
Example
For example, a variable declared within a function is only accessible within it. A variable declared outside of a function is accessible anywhere though. Consider the following code snippet:
// Exists throughout the program double
globalVariable;
void myFunction(void){
// Exists only in this function double variableA;
}
int main(void){
myFunction();
}
The snippet starts off by execueint the function "main". Then, it runs myFunction. myFunction declates the variable variableA. When myFunction exits, the variable previously declared, variableA, is no longer accessible and in fact, no longer even exists (it goes out of scope). The part of memory that it is at is probably now being used by something else. A variable out of scope can't even be returned by a function.
Using the Heap
A block of memory under complete control of the programmer is often known as the "heap". The scope problem can be solved by useing the "new" keyword to allocate memory off the heap. The following code snippet should help demonstrate this:
// This does not work
int* aFunction(void){
int localVariable;
return &localvariable;
}
void anotherFunction(void){
int* pointerLocalVariable;
pointerLocalVariable = aFunction();
*pointerLocalVariable = 34;
}
// This does work
int* aFunction(void){
// Allocate a memory off the heap
int* pointerLocalVariable = new int;
return pointerLocalVariable;
}
anotherFunction(void){
// aFunction returns the address of
// the block of heap memory allocated
int* differentVariable = aFunction();
// Store 34 in the address of allocated
// memory
*differentVariable = 34;
// Memory returned to heap by using "delete"
delete pointerLocalVariable;
As you can see in the above code, the "new" keyword is used to allocate some memory off the heap. To clarify things, the following shows how to allocate some memory off the heap: type* variable name = new type You may also notice the "delete" command. This returns the memory back to the heap. You use "delete" with the pointer variable used when allocating the memory.
All in all...
I could go into all the details and could expand the length of this tutorial, but it's already long enough. Also, excuses my long variable names - they are used to clarify if they are local or not, etc. Well, you all now have (or at least I hope so) a fairly good understanding of allocating memory off the heap, and what scope means and what the heap is. Happy coding =)
About Qt
Qt is a toolkit made by Trolltech that mainly is focused on graphical user interface (GUI) programming. It is not just a GUI toolkit, though, containing classes for network programming, database programming, and primitive graphics.
It is also unique in the way that it kind of adds its own "extensions" to C++, which are then processed by the meta-object compiler. These extensions generally make programming Qt easy and fast. Unfortunately, this also makes Qt not work with a lot of integrated development environments (IDEs). QDevelop, specifically designed to be used with Qt 4, works with Qt well, so that's what we'll be using.
Qt comes in two main editions: a commercial edition, which costs money, which allows it to be used in the development of proprietary, or non-open source and free, software, and an open source edition, which is free, and it is what you use if you are developing open source applications - this is the one we're interested in.
Installing Qt and Qt Basics
You can download Qt for the Windows, Mac, and X11 platforms here. If you're using Linux, or another Unix-based operating system besides Mac OS, then the X11 version is for you. In addition, if you're using Linux, you can probably more easily install Qt through repositories - most likely, the ones enabled by default. The packages you'll need will probably be under the names "qt4" and "qt4-devel," and any dependencies will automatically be handled if you're using a decent operating system (just kidding, Slackware and other "stable" operating system users ;)). You'll probably only need to install qt4-devel, and qt4 will automatically be installed, being a dependency.
If you're using Windows, Qt 4 will probably be installed in C:\Qt\4.*.* (replace each "*" with a version number, for example: C:\Qt\4.2.3). If you're using Linux and have installed Qt from a repository, it will probably be installed in /usr/lib/qt4 or /usr/lib64/qt4. If you're on Mac OS, then...well, I'm not sure...I don't know much about Macs...but whatever the installation directory is, it should probably be intuitive. ;) Anyway, navigate to wherever Qt 4 was installed. In the "bin" folder, you'll notice several programs. The ones that you should probably be most concerned about at this point are "qtdemo," "assistant," "designer," and "qmake." "qtdemo" lets you try some interesting and helpful demonstration programs, and it also comes with links to their source code and documentation. "assistant" is a very useful program, providing extensive information about Qt, and essentially being an easy-to-use right-there-when-you-need-it form of the Qt documentation - I highly recommend checking it out sometime. "designer" is a visual What-You-See-Is-What-You-Get (WYSIWYG) editor for Qt - you may not be using this directly much because QDevelop kind of intergrates with it...you'll see. :) And lastly, there is "qmake." Although you probably won't be using this directly much, I thought you should know a bit about it. It's a tool that generates a Makefile for you based off of information from a Qt project file (which has a file extension of ".pro"), simplifing matters grealtly - especially development across multiple platforms.
About QDevelop
QDevelop is a free cross-platform IDE for Qt programming with C++. It integrates well with the components of Qt and is easy to use. Once you get more advanced at programming in C++ with Qt, you might want to switch to using a plain text editor and a command prompt. This is because QDevelop likes things its way, and if you decide to make a very complicated Qt project file with a bunch of odd dependencies or something like that, QDevelop will likely either mess up you're Qt project file or crash, unfortunately (although it is radidly improving its stability). For now, and quite some time, though, QDevelop should be fine.
Installing QDevelop
Go to http://www.qdevelop.org/ and click on "Download." Downloading the correct version should be easy enough...except for a few exceptions. If you're using Linux, first check if QDevelop is in your repositories, and if it is, you should probably download it from there. If not, download the appropriate package from the QDevelop website, and if there are no packages available for your distribution, then just download the "Linux dynamic version with plugins."
Installation should be easy enough. If you're building from the source, make sure you have the necessary dependencies (such as Qt 4, which you should already have).
Using QDevelop
When you first open QDevelop, you'll be prompted for some the paths to the external tools it uses. "gdb," a debugger, and "ctags," which can further assist you while programming, are both handy, but not necessary. And if you're Qt installation was successful, you should be able to fill in most, if not all, of the other fields (except "make"). If you don't have "make" already I recommend getting it from here.
From there...feel free to experiment. :) A few things to note:
- If you click on a .ui file, or a file that is under the "Dialogs" menu, it will most likely be opened with Qt Designer. If you want to view the actual contents of the file with QDevelop, you can simply open it with File->Open.
- If you need to use any of Qt's non-GUI features, you can enable them through Project->Properties of [project name].pro.
- Most of the time, you'll probably want to create a Qt application that uses a main window and not a dialog. The default option in QDevelop is to create a Qt project with a dialog, though. When creating a new project, in the "New project creation" window, simply select the "Application with Main Window" option.
Where to Go From Here
I recommend reading through the Qt documentation, either online (http://doc.trolltech.com/4.3/ contains documentation for the current stable release of Qt) or through the Qt Assistant. There's a good Qt tutorial included within the documentation here, which I particularly suggest you go to.
"Hello World Tutorial
ok guys this is my first tutorial on C and hope it helps. Im not too good with C but this might help someone who wants to start learning C. What is C? C is a computer programming language, it is a successor of the language B (in case some people may be wondering, no there was no A :P).
Writing a C code in a text editor and then compiling that snippet of code should ouptut the commands you have written in C. This simple tutorial will teach you how to output "Hello World" on your screen. Compilers. To compile a C code you will need a compiler, here's a good on you can download for free: http://www.bloodshed.net/devcpp.html There are more compilers if you do not wish to use that one, you could use google in that case for C compilers.
Getting ready.
After you have downloaded and installed DevC++ open that compiler. in the new window go to : file > new > project OR click on the new project image on one of the toolbars. A small new window should pop up with: Basic|Introduction|Multimedia| Windows Application :: Console Application and the rest. well at the bottom you will see: C project C++ project. we will be making a code in C so you choose for C project. And application type, you choose Windows Application. In a small input box at the bottom of the window you insert the name of your project. We will be naming it: "Hello" but this is optional, you can name it whatever you want to. After clicking "OK" you will have to save the project somewhere.
My advise would be to make a folder with all your projects in it. After saving it you will get a window with a large code in it. Remove the code, all the code in that textarea can be removed. so now we have a new white page where we will be writing the code.
The Code.
first thing we do in C is include a header file. A header file contain all the info for using a build in functions you will need to make a functional code. The header file we will need to write or string is stdio.h This is the line on how to include this header file in your code
#include <stdio.h>
Now that we have our header file included we will move on to the printing of "Hello World". in all C codes you must define the function main(), this function is the first function that will be excecuted in the code. to declare function main we use this
main(){
Now we have our function main. the opening bracket "{" is used to open a function, in between the two brackets "{" and "}", you put the code you will run. Now for the exact command to print "Hello World" into the screen, we will use the function printf().
printf("Hello World");
This is really simple if yo look at it, first we call the printf function, and whatever we want to print onto the screen with printf we put inside double quotations. So if you wanted to print something else you just put something else in the double quotations:
printf("Hello Dude");
A small note, after every command in a C code, you must add a semi-colon. so now that we have added the printf function we will close the main function using the clsoing bracket "}" so now your code look like this:
#include <stdio.h> main(){ printf("Hello World"); }
To run your program click the compile & run button (its a button in the top left of your window with 4 colors). or you can just click F9. you may see a black screen for 0.1 seconds or something and then it closes automatically. this is because after printing "Hello World" the program closes itself. to stop it from doing this you add
system("PAUSE");
in the main function. So now your code looks like:
#include <stdio.h> main(){ printf("Hello World"); system("PAUSE"); }
"Hello World" may be on the same line as "Press Any Key To Continue". if you want this on a seperate line you ad a break line charachter "\n" in the printf function. like this:
printf("Hello World\n");
And that's it for your first C program (and my first C tutorial :P). hope this was helpfull, if not you can PM me or email me. have fun with C!!
What are they?
Pointer variables are variables that contain another variable's address. Every variable is stored somewherein the computer's memory. One might be stored at 0x120 while another will be at 0x190.
Important Operators
Here are some important operators having to do with the address of a variable: & = The address of * = (In a declaration) pointer to or (In an expression) the thing pointed at by
The & Operator
The & operator returns the address of a variable in the computer's memory. Here is an example:
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std; int main() {
int theVariable;
cout << "Address of the Variable: " << &theVariable << endl;
system("PAUSE");
return 0;
}
The output of this program should look something like:
Address of theVariable: 0x22ff6c Press any key to continue...
The exact address outputted probably won't be the same as the example, but it should be in the same general hex format.
The * Operator
Like I said before, the * operator says in a declaration, pointer to, or in an expression, the thing pointed at by. The following code snippet demonstrates the correct use of *.
int Var;
int* pointerToVar;
pointerToVar = &Var;
//pointerToVar now points to Var
*pointerToVar = 5;
//stores 5 to the addresse of Var
The snippet above demonstrates how to create a pointer variable and then assign a value to an address. When declaring a variable a pointer variable, the syntax is: the type of the variable it points at* variable name The * may appear anywhere between the type declaration and the variable's name. So, you could do:
char* aPointerVariable;
or
char *aPointerVariable;
You can also use pointer variables and the type of a function, like:
double* myFunction(){
//...do some stuff
}
Conclusion
Well, now you should have a grasp over the basics of pointer variables. I could go over offsets and more complex stuff, but then this tutorial would probably be too long, and it's called "Pointer Variable Basics" anyway. I might make a continuation of this though...
Parts: Declaring Variables Manipulating Variables Creating Arrays Summary (And Preview) Part 1 - Declaring Variables:
Note: You should add a semi-colon after every statement in C++. Spaces in C++ are usually used for clarification. In C++, you must declare a variable's type before you assign it a value (Note: cariable names my include both numbers and letters).
If you try to give a variable a value without declaring the variable's type, when you try to compile and run the program, you will recieve an error.
The types of variables are:
int,
unsigned int,
long,
unsigned long,
float,
double,
char,
string,
and bool.
Here are the definitions of each type:
int - An integer (not a fraction) that can be positive, negative, or 0.
unsigned int - A counting number that's only non-negative.
long - An integer that is very long (in some editors it is the same as int).
unsigned long - A nonnegative integer that is long.
float - A real number that takes up less memory than double but is less accurate in calculations.
double - A real number that is accurate during calculations and that may be very large; many times larger than an int variable.
char - A single character that is kind of like a string with one character.
string - A string of characters.
bool - A logical value: true of false
Here are a few examples of how you would declare variables and their values:
Example 1: int x; x = 5; or int x = 5;
Example 2: char a; a = "q"; or char a = "q";
Also, in strings, there are a few special things you may add in them:
\n - Start a new line.
\t - Tab
\0 - Null
\\ - Backslash
Part 2 - Manipulating Variables:
Here are some symbols you may or may not be familiar with
(2 means for 2 arguments, 1 means for 1 argument): + (1) Does nothing - (1) Retuens the negative of an argument ++ (1) +1 -- (1) -1 * (2) Mutiplication / (2) Division % (2) Modulo + (2) Addition - (2) Subtraction
Assignment Types:
= Means a=b
*= Means a=a*b
%= Means a=a%b
+= Means a=a+b
-= Means a=a-b
Logical Operators:
== Tests to see if the argument on the left is equal to the argument on the right
!= Tests to see if the argument on the left ISN'T equal to the argument on the right
> Greator than
< Less than
>= Greator than or equal to
>= Less than or equal to
&& Tests if the arguments on both sides are true
|| Tests if at least one of the arguments on one of its sides are true
! Tests if its argument is false
Example:
int myVariable1 = 10; int myVariable2 = 11; bool x; b = (myVariable2 != myVariable2);
The example above would make b be true. Part 3 - Creating arrays Arrays must have their type be declared too. Here is an example array: char myArray[] = {'H','I'}; To access a specific element in the array (let's use "H" for the example), you would do:
myArray[0] If you want the same element to be repeated in the whole array, you could do something like: float myArray[10] = {2.0};
That would make all 10 sections of myArray have the number 2.0. Part 4 - Summary: That should cover the BASICS of variables. I'll probably make another tutorial that has more advnaced info on variables. Preview to Stuff in the Next Tutorial:
To display strings, you would do:
cout << "string"; So to display a variable and a string, you could do: string yourName = "Bob"; cout << "Your name is" << yourName; To let the user of the program input sometthing, you do: cin >> myVariable;
Our tutorials have been submitted by our own members and staff over the last four years. They cover a range of design packages and programming languages.
Tutorials are key part of learning new skills, so we not only recommend that you try some, we suggest you experiment with the framework that they give you, don't be scared to wander from the instructions.
Click the categories below to get started!
Alternatively you can pass on your useful tips and advice to others, by creating your own.
Submit a Tutorial
If you like a tutorial, please use the "digg" button below it.
Using Notepad...
A webpage is made up of tags like this <a href=''>text</a> that is a hyperlink!
Basic HTML pages (before any tags are added) should liik like this...
### <html> <head> <title></title> </head> <body> </body> </html> ###
you would place most of your tags inbetween the <body> and the </body> tags.
To add text you would just enter text... Get it!
To add a image you would use the tag <img src='here is where you would place your image location.gif (bmp or jpg most other types are not web frendly - e.g psd)' border='0'>
To add a link you would use this... <a href='http:// link to location.html'>Text link or image</a> if you want a image there you would use that image tag [above]...
To center text place the text between this tag... <center>TEXT</center>
For Bold Text <b>TEXT</b>
For Underlined text <u>TEXT</u>
For italics <i>TEXT</i> in that <body> tag you can change the background colour text colour and link colours by changing it to <body bgcolor='#hex colour for the background' text='#hex colour for the text' link='#hex colour for the links' alink='#hex colour for the active links' vlink='#hex colour for the viseted links'> You should be able to use this to make a basic HTML page
------------- What is HTML? --------------
HTML Stands for ( H )yper ( T )ext (M)arkup (L)anguage. HTML is a language that uses codes to make your own webpage.
What do i need to get started?
-------------------------------
-Notepad
-HTML Knowledge
simple, eh?
Basics
-------
First, you use this to say your using HTML: <html> and you end it with: </html> This is the main code template that you use: <html> <head> </head> <title>TITLE GOES HERE</title> <body> Everything including codes, text, ect. goes here. this is what will be displayed on your site. </body></html> Again simple? isn\'t it?
Working With Text
------------------
This of course goes in the body. To add normal text just like \"this\" just type in what you want and it will be displayed. Text Styles- Color:
<font color=COLORHERE>TEXT HERE
you can use hex code or simply just \"red\" for example. Underline:
<u>and end it with </u>
and:
<i>Italicized</i> <s>Slashout</s> <b>Bold</b> <u>Underline</u> <sup>SuperScript</sup> <sub>SubScript</sub> <tt>Typewriter</tt>
Size:
<h[1-7]> and end it with </h[1-7]>
1 is the biggest 7 the smallest.
Hyperlink:
<a href=URL OF WEBSITE> TEXT HERE</a>
Adding a space (text):
i know it doesn\'t look like HTML but it is. dont add < > around it.
Adding Graphics
----------------
<img src=\"URL OF GRAPHIC\">
making them a link:
<a href=\"URL OF LINK\"> <img src=\"URL OF GRAPHIC\"border=0> </a>
Background:
<body background=\"IMAGE URL\">
^ That\'s for images ^
<body bgcolor=\"COLOR OR HEX CODE HERE\">
^ that\'s for a color background ^
<!DOCTYPE html PUBLIC"-//W3C//DTDXHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html> <head> <title> HTML Form </title> </head> <body bgcolor="#FFFFFF"> </body> </html>
Now between:
<body bgcolor="#FFFFFF">
I want you to type the opening tag for form
<form>
Once you done that You can choose of what to put in the form field
Here the form code:
For textbox:
Input type="text" />
For Password:
<input type="password" />
For Checkbox:
<input type="checkbox" /><
For Radio:
<input type="radio" />
For Upload File From your PC:
<input type="file" />
For Submit Button:
<input type="submit" />
Notice
If you do not want the button to say submit and want to put of what you want the button to say then do this
<input type="submit" value="Login" />
Notice You see it say
Value="login" />
That is the value where you can choose of what you want the button text to be For Button:
<input type="button" />
For Reset:
Input type="reset" />
For Hidden:
<input type="hidden" />
Notice
The input tag have no separate closing tag but it close it self using "/>" at the end.
For Textarea:
A textbox is a large box which require rows and cols attribute it look like this <textarea rows="5" cols="5">A textbox</textarea>
Last one
For Drop Down Menu:
This is very different from the other tag including the textarea To open the tag for dropdown menu use this tag
<select>
Then for the bit that will be in the box you will need to do this:
<option value="option 1">Mum</option> <option value="option 2">Dad</option> <option value="option 3">Sister</option> <option value="option 4">Brother</option>
To add more item then repeat this in number ordered:
<option value="option 5">Friends</option>
Now you see where i type mum, dad, sister, brother and friends? that is the text that going to appear in the box
Enough TAG! let put it in there form field
Again go to notepad and type this
<!DOCTYPE html PUBLIC"-//W3C//DTDXHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html> <head> <title> HTML Form </title> </head> <body bgcolor="#FFFFFF"> <form> <input type="text"/> <strong>Username</strong> </form> </body> </html>
and save it as Form.htm, then open it up and you get a clear display of what i'm talking about! So put any of them to see what it like
How to Use Form In A Appropriate Way
Now lot of people can make it look bad way and unexpected way so you gonna have learn how to use it So use the break tag to break the form in the line, it is the same as when you type a text. So try and make a registration fields like in Proboards for a good start So copy and paste this or code:
<!DOCTYPE html PUBLIC"-//W3C//DTDXHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html> <head> <title> HTML Form </title> </head> <body bgcolor="#FFFFFF"> <form> <input type="text" /> <strong>Username</strong><br /><br /> <input type="password /> <strong>Password<br /><br /> <input type="password /> <strong>Password Again</strong><br /><br /> <strong>Gender</strong> <input type="radio" /><strong>Male</strong><br /><br /> <input type="radio" /><strong>Female</strong><br /><br /> <input type="radio" /><strong>Keep Secret</strong><br /><br /> <strong>Age</strong><br /><br /> <select> <option value="option 1">13</option> <option value="option 2">Over 13</option> </select> <br /> <br /> <input type="submit" value="submit" /><br /><br /> <strong>thank you for registering At Metal Gear Solid Snake</strong> </form> </body> </html>
Phew after coding it! so save it and open it and you get a very clear image of how to use it in a Appropriate Way :smile: But it does send it to where you want to. If you want to learn how to send it then you will have to learn ASP or PHP I hope this tutorial help you people! Enjoy :) And do not RIP my tutorial
<IFRAME name='framename' src='yoururl.html' width='100' height='100' frameborder='0' scrolling='auto'></IFRAME>
Add the above tag into the page you are wanting to add your Iframe no for each of the parts... the name='framename' change this into what you want the name of the frame to be for targeting frames when hyperlinking
<A href='pagename.html' target='framename'>Text</a>
Get it... the src='yourpage.html' change to what you want the defoult page in the IFrame to be [htm or html] width='100' change to what you want the width of the IFrame to be and same with the height='100' part frameborder='0' can be changed to frameborder='1' if you want a small border aroud the inside of the frame... scrolling can be left auto! Auto=detect if your page in the frame is bigger than the frame, anly than will it show a scrollbar, Yes=always have a scrollbar no=never have a scrollbar even if the page is larger than the IFrame - I dont know why you would want to use it! :grin:
Enjoy, DanielBB
Now HTML isn't really that hard. Now let's make you your own webpage. First of all if your using windows open notepad if linux then open up text editor. Now type in:
<HTML> </HTML>
this starts your webpage. Now add inbetween those tags
<HEAD> </HEAD>
Now caps are not required. The HEAD is the top so whatever is in there is on top and the body has the bottom. Now under the head add this still inbetween the HTML tags:
<BODY> </BODY>
So far this is what is in the document:
<HTML> <HEAD> </HEAD> <BODY> </BODY> </HTML>
Now you can just add what you want inbetweenthe Head and Body tags but everything stays inbetween the HTML tags.
HTML Cheatsheet:
Bold - Type: <b>Text</b> appears Text
Italic - Type: <i>Text</i> appears Text
Underline - Type: <u>Text</u> appears Text
Strike - Type: <s>Text</s> appears Text
Link - Type: <a href="URL">Text</a> appears Text
Image - Type: <img>Image URL</img>/<img src="Image URL"> appears :smile:
Horizontal Rule - Type: <hr> appears
Tables? What are they? Tables are useful in helping store, orgainze and display data, quickly and easily. All tables start off with the <table> tag, and likewise, end with the </table> tag.
To add info to the table, you must make use of the two tags, <tr> and <td>. Look at the following HTML code, and I'll explain below it.
<table> <tr> <td>Line</td> <td>1</td> </tr> <tr> <td>Line</td> <td>2</td> </table>
The <table> tag starts off the code. To create a new row for data, insert the <tr> tag. The "tr" stands for table row. To add data into cells of that row, simply place the <td> tag AFTER the <tr> tag. Afterwards, close your tags with the </tr> and </td> tags.
You can control the width and height of the table either using percentages or pixels. <table width="90%" height="70%"> Using percentages to resize tables. <table witdh="400" height="100"> Using pixels to resize tables.
You can add many things to a table, and I will list a few of them, and how to use them. To add a border, you would do this: <table border="1"> Just insert your data and close with </table>. Border symbolizes you want a border and 1 designates the thickness of the border. The higher the number, the thicker the border will be.
Cell Padding and Cell Spacing
These two things can be confused easily, and often lead to many mistakes. First, I will explain cell padding. Cell padding increases the extra leftover space in each cell. To use cellpadding, do this: <table border="1" cellpadding="1"> The border is optional, but once again with the border, the higher the number, the more cellpadding there will be.
Think of cellpadding as putting styrofoam into a package to help protect it, which will increase its size. :tongue: Cell spacing is how much space is between individual cells. Cell padding effects the space OUTSIDE the cells, if you are lost. <table border="1" cellspacing="1"> Like with all table attributes, the higher the number, the bigger the result.
Think of cell spacing as the space between each "object" in the area. [u]Empty Cells[/u] For some odd reason, you may want an empty cell. Well, if you tried to just do this: <td>(hit space bar)</td> It would end up no cell with no border.
To create a true empty cell with no border, do this: <td> </td> The creates a non breaking space in the cell.
Cell Spanning
To have a cell span one or more row/column, you have to utilize the "colspan" and "rowspan" attributes. Colspan crates a cell spanning over many columns and Rowspan creates cells spanning many rows.
Cell Data Alignment
If you wish to align the data in a cell left, right, center, etc., use this: <table> <tr> <td align=_______>DATA</td> </tr> </table> For aligments, use "left" for left, "right" for right and "center" for center. KEEP THE QUOTES!
There ya go, a simple, yet plentiful tut on tables.
Our tutorials have been submitted by our own members and staff over the last four years. They cover a range of design packages and programming languages.
Tutorials are key part of learning new skills, so we not only recommend that you try some, we suggest you experiment with the framework that they give you, don't be scared to wander from the instructions.
Click the categories below to get started!
Alternatively you can pass on your useful tips and advice to others, by creating your own.
Submit a Tutorial
If you like a tutorial, please use the "digg" button below it.
Introduction.
In this tutorial I hope to show you what Javascript is, and what it can do for you and your visitors. Before I continue I must point out that i'm not an expert in javascript, the things you read from here are what i've read over the last year or so. Most of this introduction contains basic explanations and examples found across the internet and in books. Few things I would like to point out first before you continue on. When you come to viewing an example of code, don't just copy and paste it, type it out. From doing this you will learn to debug your code and fix any problems that arise, just a small thing that I suggest, but if you want to copy and paste, feel free to do so. :tongue:
What is Javascript and what can it do?
Javascript is a scripting language, which means that scripts included in the webpage are read by the web browser's javascript engine when the page is loaded. Javascript was created by Netscape which was originally called Livescript. There are loads of things you can do with Javascript to make your website more interesting for your visitors. From validating forms, interactive scripts, random images, popups, even make Javascript games.
<script type="text/javascript">
<!--
//-->
</script>
Note: you might see some script blocks that contain the language attribute, this was used to specify the scripting language but I believe it has been removed in HTML 4.0. The actual code you make would go between <!-- and //-->. These are to hide the script from really old browsers that cannot interpret Javascript. You may also separate the Javascript code from the HTML code by putting the Javascript code into a Javascript file. A Javascript file is just a text document with the Javascript code in it but without any <script> tags or HTML tags. A Javascript file is saved with the extension ".js". To call the Javascript file to be loaded into the web page, you would use a script block like so:
<script type="text/javascript src="http://www.mydomain.com/myscript.js"></script>
Putting Comments in Scripts.
It's always a good idea to add comments to your scripts, why? well, come months later when you decide to make changes to your script it will be easier to find the block of code to change. I have a bad habit of not adding comments to my scripts but have found it very awkward making changes to a script. Here are 2 javascript examples: One line comment:
<script type="text/javascript">
<!--
//this is a one line comment
-->
</script>
Multi line comment:
<script type="text/javascript">
<!--
/* this is an example of a comment that can be added to multiple lines. */
//-->
</script>
For the one line comment you use // followed by your comment, this is fine for short comments, but when you need to add a much longer comment you can use example 2. For example 2 you start with /* which tells Javascript to ignore everything that follows until you reach */ to close the comment. Simple enough? :)
<script type="text/javascript">
<!--
alert("Hello World");
//-->
</script>
For this small script we use the Javascript alert() function within the script block. When the web page is loaded the Javascript code causes the browser to open an alert box containing your message withing the quotes. So that's all it is, to have your message appear just place it within the alert function inside quotes. Note: it's good coding practise to end statements with the semi colon ;, although Javascript doesn't require it like some language (PHP) it's good to get in the habit of adding it.
Variables.
What's a variable? I hear you say.... Answer: A variable is a place in which you can store data. When you come to naming variables you must be aware of certain things. A variable can have any letter, digit and even the underscore _ may be used, but the variable may not begin with a digit. Example of valid variables: abcd my_variable var32123 To create a new variable, you use the Javascript "var" keyword. I'll show you with a small script.
<script type="text/javascript"> <!--
var my_message = "My First JavaScript Variable";
alert(my_message);
//-->
</script>
The text string is stored inside the variable called my_message. Then the variable name is called to the Javascript alert function that we talked about earlier, so when you run the script you will get an alert box displaying the string which is stored in the variable.
Are you a noob? Do you have no clue what JavaScript does? Do you want to learn? Fear not, for I am here to help! I'll guide you through all of the basics of JavaScript in these few, simple tutorials. :) First off, it's imperitive that you never get Java & JavaScript confused. Yes, they have similar names. However, that's the only similarity. They are two completely different languages that are meant to do completely different things. When NetScape made JavaScript, they decided to name it that since Java was already popular. It helped JavaScript grow pretty well. Now, just about every browser on the planet supports it.
First off, let's learn how to set-up a code tag. You can do this by two ways.
1.) You can embed your code with script tags.
2.) You can remotely host it. It doesn't matter which way you use, as you'll need to use script tags for both. So, let's learn how to set them up. A script tag is just an HTML element that let's the browser know that it needs to read everything in it as another type of script. It's mainly used for JavaScript.
The layout is pretty simple. <script type='text/javascript' src='myscript.js'></script>
I have color-coded this for you. The red parts are the script tags themselves. This is what tells the browser to stop reading HTML, and read a type of script.
The blue part tells the browser that the type of script it's going to be reading is JavaScript in a text format.
Now, the part is optional. If you remotely host your code, this is what tells the browser where it can find the script. It's used just like when you link to a stylesheet or image. Leave it out if you're not using a seperate script.
Now, let's learn the basics. Here's a code with some pretty simple elements of JavaScript that we'll learn:
<script type='text/javascript'>
// This line is a comment
/* This is all a comment */
var varName = "Variable Value";
</script>
Alright, the maroon parts are the opening & closing tags of our JavaScript segment. Everything you want to write in JavaScript goes between them.
The gray parts are comments. If you want to write something that the browser shouldn't pay attention to, you can comment it out, just like you comment in HTML. For a one-line comment, use //. For a multiple-line comment, start it with /*, and end it with */.
The bold navy part is what we use to define a variable. Simply start a line with "var", followed by a space, and put the variable name, shown in black.
Next, we'll add an equal sign, followed by the value of the variable. This is the part in blue, surrounded by quotes. Some things to note about variables is that you can combine different things into a variable using a + sign. For example: var
myName = "Scorpian"; var welcomeMessage = "Welcome, " + myName + ", to our site!";
This defines "Scorpian" as the value of myName. It then defines welcomeMessage as "Welcome, ", then whatever the value of myName is, and ", to our site!". This is very useful in simplifying scripts. You can also define multiple variables in one line if they all have the same value. For example:
var myMoney = myFunds = "3";
That shows that the variable myMoney will equal whatever the value of myFunds is, which we define as three. You may feel free to define as may variables as you want this way. Just separate them with equal signs. Well, that sums up the most basic of the basics for this tutorial.
Next tutorial, we'll learn how to use these variables. We'll also learn the infamous alert box, and how to use it. Stay tuned, folks. ;)
You start with <script> and end with </script> every time. It is common to use cloaking from older browsers by adding <!-- to the beginning and //--> or just --> at the end
Comments
They are parts of a script that are not read by the Javascript console, they are for humans to read and are completely ignored by the browser. There are 2 ways of writing them: // This comment lasts for one line /* This comment last until I end it with this: */
Variables
Variables are used to hold data that can change each time a page loads. Variables are often used to make it so that you don't have to write something repeated times or to make it easier on people who don't understand how to edit every part. To declare a variable you simply write the var before it. Like this: var ok = "That's ok" To understand javascript you must know the difference between a string, a number and several other different values. The ones I use the most are strings, numbers, and boolean (I think) values. Strings are like sentences, however whenever you write a string you must have it some form of quotes, like this: "This is a string in double quotes" 'This is a string in single quotes' numbers are just written like they are, for example: 5 boolean values are true or false values and can ussualy be written in one of 2 ways (I'm pretty sure): 1. True or false 2. 1 (true) or 0 (false)
Some commands
if(){} for(){} alert() function blah(){} prompt() confirm() write() For if(){} you write the statement that you want to check to see if it's true, then in the brackets you write what you want it to do if it's true. An example:
var h = 5;
if(h == 5){
document.write(h)
}
Note: I didn't use one = sign, I used two (==). One equal sign is saying what something equals, 2 is comparing. Javascript always starts counting from 0 and you need to remember that. It is a common error in alot of scripts.
Arrays
An array is something that holds multiple variables An example: var hey = new Array("Hey',"Hello","Hi","Wassup") or: var hey = new Array(); hey[0] = "Hey"; hey[1] = "Hello"; or: var hey = ["Hey',"Hello","Hi","Wassup"]. That's pretty much saying the 0th hey is "Hey" and the first hey is "Hello"
Functions
function sayIt(text){
alert(text)
}
To call the function you would do this: sayIt("hello");. This would make an alert with "hello" in it, you could change hello to whatever you want. However, you wouldn't use functions for something stupid like that. Instead you'd do something like this: document.form.checkbox.onChange = "javascript: checkIt(this)" Then the function would look like this:
function sayIt(it){
if(it.checked){
document.form.checkbox2.checked = true;
}
}
Alert, Confirm, Prompt
These are basic, preset functions.
Alert: alert("Hey"); \\Makes an alert that says: Hey
Confirm: confirm("Are you sure you wish to delete?"); Makes a confirm alert type thing. If it is chosen yes, then it will continue, otherwise it will go back.
Prompt: var size = prompt("What size would you like the image","#x#"); The "" set is the text, the second is the default in the prompt. Later you can call their answer by using the size variable.
Using an If
an if() statement is made when they are several possibilities, but you need a certain one. Or to check a value, and do something if it is, or isn't there. Here is one for making it that something only happens on one page instead of pages, because the main H&F applies to many pages:
if(location.href.indexOf(/action=profile&username)){
document.write("heh");
}
The difference between write() and adding to a TD or something else
document.write("Can be used to"); write something where the script is located. It writes there, no need to obtain properties of a TD and insert it there. For adding something to something where a script cannot be placed should be used like this:
var TD = document.getElementsByTagName('td');
TD[5].innerHTML += 'This is the menu';
or adding to a form could go like this: document.postmodify.message.value += "This is the message area";
//this is a comment
This is a comment. Comments are used to help guide someone through a script or code. The above is a one line comment. For comments that are more than one line use this /*Multiple line comment*/.
Variables - Variables are used to store data. This is very useful in javascript.
var myVariable = 5;
Let's take a look at this. var declares the variable. myVariable is the name of the newly declared variable. Next you will notice the = sign. This states that myVariable equals some value. Here, 5 is the value of my variable. The names of your variables can be anything (hello, myVariable, abc123, derfleurer, etc.). The same is true for their values. Another important thing to note is that variables are case sensitive.
var myVariable2 = "hello";
This is called a string. Keep in mind, the value of our previous variable (5) had no quotations around it. The difference is that the value of myVariable is identified as a number. If we had put quotations around it, it wouldn't have been identified by the browser as a number. To make it simple, strings are like sentences. How they're written is how they're displayed. Another thing about strings, never put a code such as prompt("",""); inside one. They cannot have quotations. If they did, then the value would be the code itself. If you wish to use a prompt, alert, etc. code as a value for a variable, DO NOT use quotations. Do as we did for myVariable.
You write variables just like text in JS. With one exception.
document.write("hello");
Here we see a basic code telling the browser to write hello in the page document. Now, as I said before, variables are used to store data. The exception to writing variables is that they will not have quotations around them. As you see below.
document.write(myVariable);
This will write the "value" of my variable onto the page. Get it? Now, onto alerts.
alert("hello");
This says to open an alert box when the page loads. In this case, the alert says hello. You can use variables here as well...heck, you'll use 'em almost everywhere (like I said, they're very useful). Next we'll take a look at prompts.
prompt("what's your name?","mike");
This calls a prompt. A prompt will have 2 parts. A question or request and an input value. The first set of quotations is the request. The second is the input value (either can be left blank). This particular one calls a prompt to the page that's asks you what your name is. The pre-set value is mike.
var myArray=newArray("my","what","a","lovely","day");
Ok, this declares a variable named myArray. The important part is newArray(). This states to create an array. Inside the parenthesis you will put your values.
How to write arrays
document.write(myArray[0]);
Ok, so you've declared your array...but how do you write it? Look at the above. We will be using the same variable as we did in our previous example. This states to write the the first value of our array. Javascript counts off from 0. So our first value will be #0. myArray[0] will write myArray's first value...which is my.
Now that you have all that down, let's cover if-then statements.
Alright, let's take a look at this. First off we declared some variables (question and answer). Then we created our if-then statement. if(question==answer){}. This statement says that if the value of question equals (==) the value of answer, execute the javascript in the curly brackets {}. What is the value of question? Well, it's not the prompt. If that were the case the value would be in quotations. The value of question is what the user inputs in the second set of quotations '4'. There are many ways to write if-then statements. You don't need to use strings or even variables. Look below, this is going to have the same outcome as our above statement.
var question=prompt('2+2=','4');
if(question == "4"){
alert("Correct!");
}
The next won't be the same. You won't get the users input but the outcome will return true (like it would in the above codes if the user gave the correct answer).
if(2+2==4){
alert("Correct!");
}
Now that you know how if-then statements work, it's time to write an if-then else.
var question=prompt("What's the password?","yokijo");
var answer="yokijo";
if(question==answer){
alert('That's right!');
}else{
alert('Better luck next time');
}
The above says that if the value of question equals the value of answer, execute the javascript in the {} brackets that follow. The new part here is else. In this case it says that if question does not equal answer, execute the javascript in the {} brackets that follow. So, if you gave the input yokijo you would recieve a message saying That's Right! and if you didn't you would recieve a message saying Better luck next time.
for(var i=0; i<5; i++){
document.write(i);
}
Above you will see our for loop for(){}. Inside we have declared a variable. I don't know why it must be declared inside the loop...I don't think there's as reason...it just does. The value of our variable is 0. The next two parts say that if the value of i is less than 5, increase i by one. We then wrote the variable in the brackets signaling to execute it only if the statement in the for loop is true.
I'm sure your wondering, "well is there a way to loop arrays?"
var myArray=newArray('1','2','3');
for(var n=0; n<myArray.length; n++){
document.write(myArray[n]);
}
Yes. As you see above, the array is being looped. What's new here is .length and myArray[n]. The .length is attached to the array myArray.length. It is now addressed as thelength/number of values in the array. So, the above is just saying n=0, n is less than the length of values in myArray, increase n by 1. myArray[n] simply addresses the array looped with n.
* how to declare javascript
* how to write comments
* how to write variables
* how to write strings
* how to write prompts & alerts
* how to write arrays
* how to write if-then statements
* how to write for loops
There is much more. But you may have to wait for my next tut.
<script>
var myPass=prompt("What's the password?","");
var theAnswer="yokijo";
if(myPass==theAnswer){
alert("Correct!");
}else{
alert("Wrong!");
}
</script>
Pretty obvious, right? First we declared some variables. myPass had a prompt value. theAnswer contains the value needed to make the if-then statement true. Neither of these variables do anything or have any meaning without if(){}. The if-then statement says that if the users input in myPass equals the value of theAnswer, execute the alert Correct! and if it doesn't, execute the alert Wrong!.
Your on your way.
The next few examples are for you to play around with and break down. If there's something you don't understand, look back in the tutorial. If your still lost, p.m. me for support.
This first one is a bit tricky. I haven't gone over some of what you will see within it. So as I said above, you'll have to expirament. I will go into detail in the next tutorial.
<script>
var myPrompt=prompt("What's your name?","");
document.write("Hello " + myPrompt);
</script>
<script>
for(i=0;i<=9;i++){
document.write(i);
}
</script>
<script>
var myPrompt=prompt("9x9=","81");
var myArray=new Array("That's right!","I'm disappointed in you.");
if(myPrompt=="81"){
document.write(myArray[]);
}else{
document.write(myArray[]);
}
</script>
Explanation
Basically, cloneNode does exactly what it says. It clones an element and all of it's attributes, that can be modified without affecting the original node.
Syntax
node.cloneNode(true or false);
If the boolean value in the function is false, it does not clone any of the childNodes of the element. Yes, you guessed it. If the boolean value in the function is true, it also duplicates all of the childNodes of the element. This is usually the value used, as if it is false, it does not keep any of the text in the element either. However, it is sometimes usefull to have an empty node.
Example
Theoretical: In some cases, you are using elements to modify other elements. In doing so, the original element is changed, and you can not use it any more. So, a way around this is to clone the element, and use it. I was recently writing a script that put 2 columns in a table in order, but to do so, I had to change the innerHTML of each element with the elements in a sorted array. However, the elements in the array, were the same elements I was changing, so the elements in the array were being changed as the original ones were. This isn't what I wanted, so I cloned each row, and placed it in the array.
Real:
<html>
<body>
<p>Hello <b>there</b></p>
<p>Hello <i>ereht</i></p>
<script type="text/javascript">
<!--
// simple example
// lets put the bold there in the italic ereht
// there are better ways of doing this, but it is an example :P
var element = document.getElementsByTagName("p")[0].cloneNode(true); // why true?
document.getElementsByTagName("p")[1].lastChild.innerHTML = element.lastChild.innerHTML;
//-->
</script>
</body>
</html>
As you can see, cloneNode has its uses. Be carefull not to use it with something that has an id, as it will clone it. We don't want that, do we?
createDocumentFragment() is basically somewhere to store your newly created nodes before you append them to the document, then when you are ready to append all the nodes to the document, all you need to do is 1 append and they all get added.
Creating a fragment is extremely easy. Have a look at the example below to see how a fragment is created.
<script type="text/javascript">
<!--
var docFragment = document.createDocumentFragment();
//-->
</script>
Simple see? Nothing to it, you now have somewhere to store your new nodes. To add nodes to the fragment, all you need to do is append the childs to the fragment. See the example below to understand what I mean.
<script type="text/javascript">
<!--
var docFragment = document.createDocumentFragment();
var txt = document.createTextNode("my text node");
docFragment.appendChild(txt);
//-->
</script>
For the example above I created a new text node, and then used appendChild() to append the new text node to my fragment. So now my fragment holds 1 node. I could add more if I wished.
So what's the point in using it when you can just keep using appendChild()? To be honest I haven't found a big need to use it, but when I have, I use it when I do a lot of appending to the document. So instead of do 15 appendChild()'s at the end of my script, I can just do the 1, which would be to append the fragment, because throughout the script I will be appending them to the fragment, so when it comes to the end of my script all the new created nodes would now be stored in my fragment, just a matter of appending it to the document.
I'm sure there is more use for it then that, just that I haven't found a big need for it.
For DOM, createElement is probably one of the handiest of all methods.
For this tutorial, we will create an image append it at the end of the document.
<script type="text/javascript">
<!--
var nImage = document.createElement("img");
//-->
</script>
Now that we have out created element, let's assign it the 'src' attribute.
<script type="text/javascript">
<!--
var nImage = document.createElement("img");
nImage.src = "http://www.solidsnakedesigns.com/images/smileys/smile.gif";
//-->
</script>
Now, for this tutorial I am just using the ' :smile: ' smilie as an example. This is optional, but it's something that I always like to do. Add a small portion give the newly create image no border.
<script type="text/javascript">
<!--
var nImage = document.createElement("img");
nImage.src = "http://www.solidsnakedesigns.com/images/smileys/smile.gif";
nImage.border = '0';
//-->
</script>
Now that our image is created and out attributes are set, let's append it to the document.
<script type="text/javascript">
<!--
var nImage = document.createElement("img");
nImage.src = "http://www.solidsnakedesigns.com/images/smileys/smile.gif";
nImage.border = '0';
document.body.appendChild(nImage);
//-->
</script>
There you have it :smile: . If you're using createElement to make a lot of objects for appending, then check out createDocumentFragment() by Peter.
createTextNode() is pretty simple to use for creating text nodes. Check the example below.
<script type="text/javascript">
<!--
var myText = document.createTextNode("hello world");
//-->
</script>
As you can see we have a script with a variable called "myText" which is holding the text node we have just created. Creating text nodes with createTextNode will just be plain text, putting in tags to make it bold, italic etc, will not work, you will need to do more work with the text node to give it style. So, you have created your text node, but what do you do with it now? Well, now that you have created your text node, you need to append it to the document. Take a look at the script below.
<div id="mydiv"><div>
<script type="text/javascript">
<!--
var myText = document.createTextNode("hello world");
document.getElementById("mydiv").appendChild(myText);
//-->
</script>
Now, just above the script is a small bit of html, a div element, this will be used to place our new text node inside of it. Reason for the id="mydiv" is so that we can reference the object using getElementById. We then need to use appendChild() so that we can insert the new text node into our div element. appendChild() works by inserting the new node at the end, all you need to do is add a parameter, so in this case the parameter is "myText" since that is the new node we wish to add to the document. Once you get a good understanding of creating new text nodes and appending them to the document, you can then look into give the text some style. An example of what I mean is below.
<div id="mydiv"><div>
<script type="text/javascript">
<!--
var myText = document.createTextNode("hello world");
var font = document.createElement("font");
font.style.color = "red";
font.appendChild(myText);
document.getElementById("mydiv").appendChild(font);
//-->
</script>
Basically same as before, but this time we are adding the new text node to a font node we have created. var font = document.createElement("font"); The variable "font" now holds a new node we have just created, that new node being a font element. font.style.color = "red"; I wanted to make the new text red, so I set the font style color to red. font.appendChild(myText); All that is left is to add the text node to the font node, so the text node will be a child of the font node, we do this by using the appendChild() again, so now we would have something basically like....
<font style="color: red;">hello world</font>
....that now needs to be added to the document, so just like we did before, we appended the text node to the div, we will do the same but this time we will be appending the font node which already contains our new text node. document.getElementById("mydiv").appendChild(font); And finally, the last line to append the font node to the div container. Basically it, got any questions feel free to ask on the forum.
A function is a bit of code that can be used once or many times, and is made of statements to perform tasks. Each function you create in your script needs to have a unique name so that they can be called in your script. Below is a simple example of a function.
<script type="text/javascript">
<!--
function myFunction(){
alert("hello world");
}
//-->
</script>
If you take a look at the script you will see that a function is made by using the "function" keyword before the function name "myFunction", which is then followed by parentheses and an open brace. The statements for your function go on the next line, then finally you close the function with a brace. Pretty simple isn't it?
So, you have made your function, but how do you call it? Easy, take the script above, when you call the function it will show an alert box displaying the message inside the quotes "hello world", now to call it, all you need to do is place myFunction() anywhere under it, placing it above the function will cause an error because the function hasn't loaded, a way to avoid that is to place functions inside your <head> tags and then you can call them anywhere in your document. take a look at the script below which shows you how I called the myFunction().
<script type="text/javascript">
<!--
function myFunction(){
alert("hello world");
}
myFunction();
//-->
</script>
That's very basic way of calling the function, there are loads of other ways to go about calling them. A common way is to have the function run when the document has loaded, so to do this you could place the function inside your <body> tag using the event handler "onload", to understand what I mean take a look below. <body onload="myFunction()"> Now when the document has loaded you will then receive the alert box displaying the message. That's pretty basic, functions aren't limited to the example I have shown, we can also pass information back to the function, take a look at the example below.
<script type="text/javascript">
<!--
function myFunction(message){
alert(message);
}
myFunction("hello world");
//-->
</script>
As you can see the function basically stays the same, only now the function "myFunction" has a parameter added "message", this is a function argument, so any information passed to the function is stored inside the "message" variable. To pass information to the function you just need to input some data. For this example we kept with "hello world", so if you look at myFunction("hello world"), all this is doing is passing "hello world" to the function which then gets alerted. So, what's so great about passing information back to a function? Many reasons why, and i'll show you an example.
<script type="text/javascript">
<!--
function myFunction(message){
alert(message);
}
//-->
</script>
<input type="button" name="button1" onclick="myFunction('This is button 1');" />
<input type="button" name="button2" onclick="myFunction('This is button 2');" />
In the example above we have 2 buttons, each button is calling the same function but each button will display a different message when clicked on. We use the event handler "onclick", what this does is run the function when the button has been clicked on. So as you can see, with passing information back to a function like the example above you can have it perform a task, this saves having to write out the whole function again and again. Just a brief tutorial on functions, there is a lot more to be learnt about functions, but for now the basics will do.
getAttribute()
getAttribute() returns an attribute's value. It can be very useful and is really easy to learn. Here's the syntax: getAttribute(attribute) Here is an example for a document that had a table with a width of 300 and an id of "myTable":
<script type="text/javascript">
var theTablesWidth = document.getElementById("myTable").getAttribute("width");
</script>
The example above would make the variable theTablesWidth be equal to 300 because the table's width was 300.
setAttribute()
setAttribute() changes an attributes value by giving it a new one. It is extremely userful. Here's the syntax: setAttribute(attribute, theNewValue) Here is an example for a document that had a table with a width of 300 and an id of "myTable" (the same situation as before) >>
<script type="text/javascript">
document.getElementById("myTable").setAttribute("width","200");
</script>
The above example would change the table's width to 200. Here is another example for lets say I had a hyperlink with an id of "myLink" that linked to http://ssdesigns.proboards17.com:
<script type="text/javascript">
document.getElementById("myLink").setAttribute("href","http://www.solidsnakedesigns.com");
</script>
The above script would make the link that used to go to http://ssdesigns.proboards17.com now go to http://www.solidsnakedesigns.com.
removeAttribute()
removeAttribute() removes an attribute. It may be useful if you want something to change to the default setting. Here is an example for a document that had a table with a and an id of "myTable" (the same situation as before) >>
<script type="text/javascript">
document.getElementById("myTable").removeAttribute("width");
</script>
The above example would remove the table's width attribute, setting it to the default width.
Conclusion
Combining the powers of getAttribute(), setAttribute(,), removeAttribute() can give you pretty complex websites. Maybe you use getAttribute() to get a table's width and store it into a variable, and then use setAttribute() to increase the table's width by 100 pixels.
Hope you all enjoyed the tutorial and happy coding!
One of the key elements in javascript codes is getting various elements from the HTML code. This tutorial will cover a few of the getElement types.
Example: What Does A getElement look like?
<script type="text/javascript">
document.getElementById('box').style.display="none";
</script>
In the above example, I've assigned the div that has the ID of box certain attributes. That's just a little thing to think of till the end of this tutorial... ;)
getElement Opening
A getElement handler is always opened by document., which means that it is getting the element from the current document. The document. is used in other JS methods, such as write().
getElement Closing
A getElement handler is always closed with brackets (A.K.A () ). You can either put the name of a variable into them or something enclosed in quotes. That something will depend on the type of the getElement.
getElements
Yes, there are also getElement types that are turned into plurals. Why? Because they repeat themselves or can repeat themselves throughout the document. getElement types that are turned into plurals will not be handled like single ones. These will either have to have a number assigned to them or be put into a loop. Below is an example of both with explanations.
The only things I want you to notice in the above example are that the getElement is in plural and that there are square brackets after the closing brackets that include in them a number. Those square brackets with the number are the thing that assigns the number. The number of a certain element is determined according to the amount of times the same element repeats itself before. So, if you count and get to element no. 36, it'll actually be no. 35 in javascript.
Again, I only want you to notice a few things. They are listed below in order of appearance:
1. I inserted the plural getElement into a variable. Why? The name I assigned to the variable is much shorter, and as the getElement repeats itself a few times in the code, it is easier to insert a variable instead of the actual thing.
2. I'm using a for loop in this code. If you do not know what it is, I would suggest looking into derfleurer's tutorial. Back to the subject on hand, the loop will repeat as long as it is smaller than the length of the plural getElement. What is the length? The length is the number of times the element repeats itself. So basically, the loop will go through all the repetitions of the element that is referred to.
3. The if statement will determine what number of repetition to stop on. It'll actually turn the variable stated in the for loop to one or only a few numbers, meaning that you'll be in a level similar to the one in the first example. The difference is, you don't need to count. ;)
4. A reference to element with the set number/s in the if statement. It's pretty similar to the example in the beginning of the tutorial. The difference is that it's a plural getElement, thus you have the square brackets.
getElementById('ID')
Now to the first type of getElement I will be talking about: by id. If you are reading this tutorial, you probably have some basic knowledge in HTML, meaning that you know that various tags can have ids assigned to them. This type of getElement will search for the assigned ID (see the red part in the title), and will then use what it located to set various attributes for it. getElement attributes will be covered later on in this tutorial. Note that getElement by id will be the only non-plural getElement I will be referring to in this tutorial. The reason for it not to be plural is that you can only assign an id to one element at a time.
Side Note: The getElement by id is frequently used to hide things (see attributes section).
getElementsByName('NAME')
The next type of getElement I will be talking about is a plural one: by name. Names are usually assigned to form elements, so you will not be using this type of getElement much (find out why in the forms section). Remember: when using this type of getElement (plural), you must do what the plural section says.
getElementsByTagName('TAG')
The last type of getElement is the most used and most complicated: by tag name. This type of getElement can be used to locate any type of tag in your HTML document, from a simple b tag (bold) to an option tag (part of a drop-down). That can probably answer the question that you were asking yourselves when I said that this is the most used getElement, which was: why? Back to the point, you can replace the red TAG in the title with any tag name that exists. Remember: when using this type of getElement (plural), you must do what the plural section says.
getElement Attributes
getElement attributes are added in the following way:
getElementType.Attribute.Sub-Attribute (if any)="VALUE"
Note: The brown parts are attributes written in their case sensitive form.
Useful Resource: Microsoft's Reference Properties (Attributes) Library
Attribute:style - Below are Sub-Attributes and their Description
display:The most common values are inline, block and none. The block will add spaces on the top and bottom of the element, such as happens with the paragraph tag. The inline will do the exact opposite. The none will make everything inside the element invisible, and is mostly used with divs.
backgroundColor:This will assign a background color to the element. The value is set to a hex.
color:This will assign a text color to the element. The value is set to a hex.
To Make Long Things Short:Style is actually a "css in HTML" tag. Any css attribute can be used in it. The way css attributes are "translated" to JS can be found on the website of Microsoft.
Attribute:parentNode - This would be best explained with an example. <table><tr><td></td><td></td></tr></table> Look at the td tags. They are surrounded by the opening and closing tags of the tr. So the tr is "hugging them". Thus, it is the parentNode. Along the same lines, the table is the parentNode of the tr. Basically, the tags that wrap certain tags are their parentNode. Can you guess what the childNode is?
What To Do With parentNode? The parentNode is actually an additional part of the getElement. Consequently, it can have attributes, just like a regular getElement. That means that you can have the parentNode handler appear multiple times: getElementType.parentNode.parentNode.parentNode.attribute.and so forth.
Are There childNodes Too? Yes, childNodes are the exact opposite of parentNodes. Using my example, the tr is the childNode of the table and the td is the childNode of the tr. If you have noticed, the brown colored text in my question is a plural, meaning that the childNodes attribute needs to be in a loop. Let's see an example of how it's implemented.
childs=myTD.childNodes;
for(t=0;t<childs.length;t++){
if(childs[t].width=="66%"){
alert('Width Match!');
}
}
</script>
In this example, you might notice that I first got the TD element and assigned it a number. Then, I assigned that getElement a childNodes attribute. Afterward, I looped through the childNodes to find the one that I'm looking for. Like I explained above, parentNode (and thus also childNodes) is part of the getElement, so all getElement rules apply on it, including finding the needed one with a loop or assigning a number.
Attribute:className - There's no need to elaborate much about this attribute. The className attribute is quite obvious: it is used to assign a certain class to an element.
Attribute:width - Again, there's no need to elaborate much about this attribute. What it does is pretty obvious: assign a width to the referred to element.
Attribute:innerHTML - This attribute is used to make various actions with the HTML or text that are inside the referred to element. Below are Sub-Attributes and their Description.
replace:Used to replace parts of the contents of the referred to element. The way this attribute is used differs from the standard.
First, notice that I wrote that the contents of the element equal the replacement. Second, I would like you to notice the replace attribute has brackets next to it, with 2 words in quotes and a comma between. The left part is what the code looks for and the right part is what it will be replaced with. All the rules of document.write() apply on the contents of the quotes (including variable insertion).
Wait, I Think I Know What's Going On Here!
If you're thinking that all HTML attributes can be referred to (according to the above explanations), you are almost right. There are two HTML attributes that I know of that cannot be referred to when using the getElement tag: name (see why in the forms section), and id. There is a small problem that can easily be fixed with referring to HTML attributes: how do you know what the javascript case sensitive form of it is? I'd suggest using Microsoft's "library" which has all of the attributes in it with their HTML form and JS translation.
Attribute:nodeName
This will return the tag name of the element you are referring to. This attribute is only used either in an if statements to check the nodeName or to return the nodeName (with document.write for example), it cannot be set or reset.
Get An Element Inside An Element
Many elements have other elements inside them. For example a td sometimes has a font tag or a b tag in it. You can get that element using the childNodes attribute, or you can follow the below example.
td.getElementsByTagName('b')[].innerHTML="Blah";
</script>
I would like you to notice the row below the variable. You can see that I took the getElement and assigned it another getElement as an attribute. The same rules of the regular getElement apply on a getElement inside a getElement.
To End This: How Do I Write Each of the getElement Types?
By Name: document.getElementsByName('NAME-OF-ELEMENT')
By ID: document.getElementById('ID-OF-ELEMENT')
By Tag Name: document.getElementsByTagName('TAG-NAME-OF-ELEMENT')
The reactions between forms and JS are based on one of the getElement types: by name. You probably remember that I said you will not be using the byName type much because names are usually assigned to form elements, and I will now tell you that what I said wasn't accurate. Why? Look at the below code and try to find the answer by yourself.
Doesn't that look awfully familiar? There's a document. at the beggining and a replace attribute. So, what is that actually? The above is a referral to a form and one of it's elements. Let's translate that to a getElement.
Both codes would actually do the same thing, but the first one is quite a few lines shorter. My point is, the first one is actually a getElement, but in a shortened form without loops or number assignments. In order of appearence: the postForm is the name of the form that we are referring to and the message is one of the fields of that form. That's the way we write things when we refer to various form fields in javascript. Forms have only one attribute that I can think of which does not appear in the actual HTML code which is: submit. If you make a button and make it's onclick equal to: document.postForm.submit(), the form named postForm will be submitted when the button is clicked.
I hope my explanations were clear enough and that I covered all the subjects that should be covered. Fell free to PM me if you want me to elaborate on a certain subject, improve my explantions, or add something new to this tutorial that seems missing to you.
~The Dog Monster
This should be a very quick tutorial explaining how to use "hasChildNodes()".
When used, hasChildNodes() will return true or false if the node has any child nodes. A child node could be anything from a bold element to a table, check the example below to show how it works.
<div id="parent"> </div>
<script type="text/javascript">
<!--
var divObj = document.getElementById("parent");
if(divObj.hasChildNodes()){
alert("Node has child nodes");
} else {
alert("Node has no child nodes");
}
//-->
</script>
Pay attention to the div element above the script, if you notice, there are no elements inside of it. In the script we start of by storing the object in a variable called "divObj" by grabbing the div id using getElementById. Now that we have the object we wish to test on, we then create an if else statement to find out if the node (the div object) has got any child nodes.
Because the div has no child nodes, when we come to execute our script we will get an alert box with the message "Node has no child nodes", this is because the div element has no child nodes. Check the other example below that is the same script except the div element has got child nodes this time.
<div id="parent">
<b>text</b>
<i>more text</i>
</div>
<script type="text/javascript">
<!--
var divObj = document.getElementById("parent");
if(divObj.hasChildNodes()){
alert("Node has child nodes");
} else {
alert("Node has no child nodes");
}
//-->
</script>
Now, this time the div element has got 2 nodes, a bold element and an italic element, this time when we execute out script the statement will return true and we will get the alert box with the message "Node has child nodes".
The insertRow() and insertCell() functions are used to add rows (tr's) and cells (td's) into a table which is already on the page. Here's a small table code on which we will be using insertRow() and insertCell().
<table id="table"> <tbody id="tbody"> <tr> <td> Cell Info1 </td> </tr> <tr> <td> Cell Info2 </td> </tr> </tbody> </table>
We have 1 table, 1 tbody, 2 rows and 2 cells in this example. You don't need to add a tbody tag when creating a table in HTML, but when you use functions such as insertRow() where you will be adding rows, you have to add them to the tbody and not the table. Because it is the tbody that actually holds the rows and the cells, not the table. As you can see, I have added a ID to the tbody tag, if there is no ID on the table or tbody tag you can use the "getElementsByTagName" function. Let's add a row and a cell to the end of the tbody.
<script type="text/javascript">
var tBody = document.getElementById('tbody');
var iRow = tBody.insertRow(2);
var iCell = iRow.insertCell(0);
iCell.innerHTML = 'Cell Info3';
</script>
Now let's break the code down :)
var tBody = document.getElementById('tbody');
Gets the tbody tag with the "getElementById" function and assigns it to the variable "tBody".
var iRow = tBody.insertRow(2);
var iCell = iRow.insertCell(0);
The argument you pass on in the insertRow function is a integer representing the location of where you want to add the row. Because we want to add a third row, remember we start counting at 0 with javascript, we add a 2 as the argument. If you, instead of the 2, inserted a 3 as the argument, the code would return a error. Because you can't add a fourth row if there is not yet a third one ;). So the newly added row is assigned to the variable "iRow". We then add a cell to that row with the insertCell() function. The arguments work the same here as with insertRow(), only this time they're for cells :P.
If you are uncertain how many rows there are a the tbody and still want to add a row at the end of the table. You can use ".rows.length" which you add after a grabbing a tbody: "document.getElementById('tbody').rows.length" This will return a integer value, but this method does not start counting at zero, so with "document.getElementById('tbody').rows.length" it would return 2 which we can also put in the insertRow() function as shown in the example (where we used 2), to add a row to the end of the table. Here's how we can use this method:
<script type="text/javascript">
var tBody = document.getElementById('tbody');
var iRow = tBody.insertRow(tBody.rows.length);
var iCell = iRow.insertCell(0);
iCell.innerHTML = 'Cell Info3';
</script>
See how I added "tBody.rows.length" as the argument of the insertRow() function? If you grabbed a table instead of the tbody, and you want to use these 2 functions, you can use ".firstChild". So it would look something like this:
<script type="text/javascript">
var Table = document.getElementById('table');
Table.firstChild.insertRow(2);
</script>
Even if you can't see a tbody tag, it is always there, even if you don't add the tag itself. So that's basicly how these 2 functions work. Have fun with them ^_^
isNaN() is used to check if the value passed as the parameter is not a numeric value. NaN means not a number. So, isNan means is not a number.
An example where this could be used is in a page submission script. Here is a simple example of it being used in an if statement.
<script>
var let = "letters"; // this is not a number
//checks to see if it isn’t
if(isNaN(let)){
alert("Please enter a number"); // if it isn’t it displays Please enter a number
} else {
alert("You entered a number"); //if it is it displays You entered a number
}
</script>
In the first example this can be used to alert the user to hit back in there browser and enter a number if the code is changed to do so. You now know how to use isNaN. I hope you can find some uses for it.
Introduction
Welcome to the javascript objects. By now you should already have a firm grasp over javascript basics. Which you might be wondering what the heck they are. An object is the to me the equivalent of an OOP class. I'm sure you've heard of and used several objects before, most likely without even realizing it. Perhaps they will ring a bell: String Array Date Number
I'll go over how to modify the existing ones and how to create your own.
A bit more about the terms
Object - A class/constructor
Instance - A certain instance of an object
Property - A variable held by an instance/object
Method - A function held by an instance/object
this - It refers the instance inside of methods and properties.
Prototype
Prototype is the key to being able to edit existing objects such as string or array. I'll start off with an example of a method:
String.prototype.tell = function() {
alert(this);
}
Now, you first might be wondering what this does and how to use it. Which brings me to another example:
var example = 'This is an instance of a string.';
example.tell();
The output of example.tell() would be "This is an instance of a string." It simply alerts the value of the string. You might also question as to why it is example.tell() instead of String.tell(). The simple answer is this: When using objects you will most likely have several instances, since you will most likely want functions that work with the value of the instance. One more example just to push you in the right direction:
Number.prototype.dbl = function(){
return this * 2;
}
var x = 5;
alert(x.dbl()); //Will alert 10
Creating your own objects
Like last time I'm going to start with an example, it's fairly simple and you should be able to get the general idea of how it works:
function Person(first,last,age){
this.first = first;
//Properties
this.last = last;
this.age = age;
this.greet = function(){//Method
alert('Hello my name is '+this.first+' '+this.last+'.');
}
}
var john = new Person('John','Doe',35);
john.greet();
alert(john.age);
//Alerts 35
var jill = new Person('Jill','Doe',64);
jill.greet();
alert(jill.age);
//Alerts 64
There it is, a very simple custom object. The Person object has a total of 5 properties which are first, last, age, prototype, and constructor. Prototype and constructor are default properties included in every object. It has only has the one method of greet. Custom objects are used to make things go faster. Imagine if you had to do something like this for each person instead of using the Person object when you have 500 people:
var johnFirst = 'John';
var johnLast = 'Doe';
var johnAge = 35;
function johnGreet() {
alert('Hello my name is '+johnFirst+' '+johnLast+'.');
}
Summary Overall javascript objects aren't all that touch. It just takes a bit of time to read and experiment with. I challenge everyone who reads this to modify an existing object and to create their own object that has nothing to do with my Person object.
This tutorial will teach you how to target cells on Proboards forums, and will help on other forums and websites as well. First, let me put up a small code.
<script type = "text/javascript">
var td = document.getElementsByTagName('TD');
for(t=0;t<td.length;t++){
if(td[t].width == "1%" && td[t].align == "center" && td[t].className == "titlebg" && td[t].innerHTML.match(/Topics/i)){
td[t-1].innerHTML="FORUM NAME HERE";
}
}
</script>
Let's go through this code, line by line. First we start the code with <script type = "text/javascript"> obviously. Next line: var td = document.getElementsByTagName('TD'); sets up a Variable named "td" and assigns it to an element 'TD' which means a table cell. Basically now, evertime we bring up 'td' it will refer to a table cell. The next line for(t=0;t<td.length;t++){ first makes a variable, "t" then it gives it a value of 0. Then it says if it's lower than the value of "td" keep increasing it.
Just to make it easier, it's going to loop through all the table cells on the page. note the "{" this means anything { between } will happen IF for(t=0;t<td.length;t++) is done, which it automatically will be. But no need to worry about that. Next line: if(td[t].width == "1%" && td[t].align == "center" && td[t].className == "titlebg" && td[t].innerHTML.match(/Topics/i)){ This is describing what table cell we're trying to grab. In this case it's the Title Bar of a proboards forum. First, it says it's width is 1% then it says it's aligned to teh center, then it says it's class is titlebg, then it says the name is topics. Then the next line says td[t-1].innerHTML="FORUM NAME HERE"
Basically, since in the previous line we described what the variable "td" looks like, here we are saying, replace the table cell right before the cell 'td' is assigned to, and replace it with "FORUM NAME HERE". So, it says td[t-1], that means the variable td meaning the cell, and the variable t, meaning the whole description above. It's a little hard to understand, but still good for makin simple codes. Really easy, and when making Proboards Hacks, EXTREMELY usefull. Hope this helped. If you have any questions, please PM Me. Regards Nemo™
Introduction:
By now you should have read my tutorial on javascript objects and be able to create and manipulate objects. This is not that complicated if you already understand javascript objects and should be very easy to learn.
The Reasoning:
As objects shorten code, so does inheritance. Inheritance allows multiple objects to share properties/methods of a parent object. In a way javascript objects can have multiple parents, but not in the traditional sense. That is they do not officially have 2 or more parents, but they inherit from 2 or more objects.
Let Us Begin:
Making javascript objects have inheritance is really just a few lines that doesn't take long. Let us start off with our person object:
function Person(name,age) {
this.name = name;
this.age = age;
}
Now, what if we have two types of people that still need to have the properties of the person object? We could do the slow way and define those properties in each object or we could use inheritance. Here is another example assuming the person object is in existence:
function Student(name,age,grade,gpa) {
this.grade = grade;
this.gpa = gpa;
this.parent = Person;
this.parent(name,age);
}
function Employee(name,age,job) {
this.job = job;
this.parent = Person;
this.parent(name,age);
}
That is the way you would do it with inheritance. With so few properties and no methods, it's not that big of a deal, and is in fact more lines just because this example is not that practical. However, with more properties and methods using inheritances the best option.
Multiple Inheritance:
As was said before, objects can have multiple parents through 1 of 2 ways. They can have the equivalent of grandparents by only inheriting one object itself, but since the parent object also inherits the properties/methods of both will be assigned to the grandchild object. The other method is to have multiple parents declared in the object. All you really do is the same method as above, except 2 or more separate times.
Traditional Inheritance:
Multiple inheritance is not technically supported because objects can only have 1 true parent, while they can inherit properties/methods from multiple objects. The reason I use multiple inheritance is because it is a generally close term to what the method of giving an object properties and methods from multiple object. The way to define a traditional parent is like so:
Student.prototype = new Person;
To be honest I have found no use for this as all my objects have arguments.
Summary:
Inheritance can be useful when you have a bunch of properties and methods that need to be shared from various objects. I hope you learned something from this and can find a use for it.
parentNode is used to get the most outer node, think of parentNodes as containers, in the container you have child nodes, to see what I mean, take a look at the example below.
<div id="parent">
<b id="child">My text</b>
</div>
With the little snippet of HTML above, you have the parent node being a div container, in that container you have "child", that child being a bold element. If you were to grab the bold element by the id (getElementById()) and ask what its parent node is, the information sent back to you would be a div. Check the script below which gives you an example of how to do this.
<div id="parent">
<b id="child">My text</b>
</div>
<script type="text/javascript">
<!--
alert(document.getElementById("child").parentNode.nodeName);
//-->
</script>
With that script above we are telling the script to tell us what the node name is of the parent. So when we run the script, what happens is that we will get an alert box with the name of the parent element, which will be "div", if we didn't use nodeName after parentNode, we wouldn't be able to tell what the element is, all you would get is "[object]". With parentNode you aren't just limited to finding 1 parent,
child nodes can also be parents, take a look at the example below.
<div id="parent">
<div id="childparent">
<b id="child">My text</b>
</div>
</div>
With the above HTML we have 2 parents and 2 childs. The first div "parent" is a parent of the second div that is nested inside, so the second div is a child of "parent". Inside "childparent" we have the bold element "child", this is now a child of "childparent". So how do we access the childs parent parent element? Simple, check the script below.
<div id="parent">
<div id="childparent">
<b id="child">My text</b>
</div>
</div>
<script type="text/javascript">
<!--
alert(document.getElementById("child").parentNode.parentNode.nodeName);
//-->
</script>
Notice the 2 parentNode's? "parentNode.parentNode". The first parentNode is the div with the id "childparent", because we want to get the most outer parent element, we need to go out even further, so by adding another parentNode we reach the div with the id "parent".
With parentNode you aren't limited to just finding an elements nodeName, you can do more then that, for example, you could grab the parent node which contains the bold element, and then append a new node onto the end. Internet Explorer comes with its own version called parentElement, but for cross browser scripts I suggest you keep with parentNode.
What is Recursion?
Recursion is an alternate method of performing something instead of iteratively. Iteration is the standard method of looping with something like while, or for, I'm sure that all of you know the drill. What you do with recursion is have a function call itself with a modified argument.
So How Does It Work?
One of the more common ways to demonstrate that is with a factorial, which is exactly what I'm going to do. As you know, a factorial is a number times all the whole numbers between it and 0. Lets go over the iterative method:
function factorial(x) {
var work = x;
while(x > 1) // Note that this is only this way because
{ // 1 * x = x, so there is no need to multiply by it
work *= (--x);
}
return work;
}
As you can tell, this is probably the standard, normal way of doing it. But we can use recursion to make this code better:
function factorial(x) {
if(x > 2) return x * factorial(x-1);
return 1;
}
You see how a function can use itself to further perform its own duties? Its quite a useful method, and works rather well. From this you may be thinking that this is only useful for math and things like that, but once again this can be used for anything.
A DOM Example
Recursion can be used to perform the task of finding the exact pixel location of an object on the screen. Here is the code:
function getPosX(elem) {
if(elem) return elem.offsetLeft + getPosX(elem.offsetParent);
return 0;
}
function getPosY(elem) {
if(elem) return elem.offsetTop + getPosX(elem.offsetParent);
return 0;
}
Introduction
Regexp, or Regular Expressions are used to grab information based upon characters. It is much like split except easier in some ways are more complicated in others. It is made to only accept the kind of data you allow it to. It can be used for email verification and many other things. The cheatsheat below tells what each character does.
Basic Syntax
/regexp here/ The first slash is the beginning and the last slash is the end. You can add 2 letters, known as modifiers, after the last slash if you want. What they are and do: i-matches any case g-global search, this mean it doesn't stop after one. However, several times you must escape something. In the cheatsheat you may notice that the question mark does something. To get the litteral question mark you would do: ? A slash escapes any character's special value (besides those including a slash, like w). If you have another forward slash: / is the proper syntax. Or for a back slash: .
New RegExp
This is the syntax to make a variable regular expression: var regname = new RegExp(\"regular expression\", \"modifiers\"); The modifiers are the letters listed above. You can put either i, g, or gi.
Matches
You can select matches from parenthesis to obtain certain values. Lets say you have this somewhere on the page: A: 56 You'd then use this regexp to match it: /A: (n)/ Then you could output/use the value: document.write(RegExp.$1);
Greedy | Non-Greedy
This is a very commonly used idea. If it is greedy it will take as much as it can with still matching, where as non-greedy would take as little as it could. A common example might be in UBBC/html tags. If you want to match anything lets say the image url from an UBBC tag, and image UBBC tag.
The post/comment:
<img src=“http://blah.com/asdf.gif /> asdf <img src=“http://blah.com/jkl.gif />
Greedy would match:
http://blah.com/asdf.gif" /> asdf <img src=“http://blah.com/jkl.gif
Non-Greedy would match:
http://blah.com/asdf.gif
So how do you set the difference between greedy and non-greedy?
Well when you use a plus or * you just leave it to make it greedy and you add a ? after to make it non-greedy. So non-greedy would be: +? or *?.
Greedily match paragraph tags:
/(<p>|<P>)(.+)(</p>)/i
Non-greedily match:
/(<p>|<P>)(.+?)(</p>)/i
One last example
/^[w-.]+@[A-Z0-9-.]+$/i I'm just going to quickly break this down. / - beginning of regex ^ - starting at the begining of the string [w-.] - match a period, a dash and any letters, numbers, and underscoreds + - 1 or more of the previous @ - the at sign [A-Z0-9-.] - any letter, number, dash, or period. + - 1 or more of the previous $ - end of string /i - end of regex