Basic JavaScript tutorial

Posts 15 of 5 · Page 1 of 1
Basic JavaScript tutorial
I'd like to start by saying I don't like JavaScript. I'd just like to introduce anyone who is interested to very basic concepts in JavaScript. All the code I will post will be tested, so if you do something and it doesn't work, it's YOUR fault, not mine.

For your first lesson, let's make an "alert" dialog box.

Open up notepad and type:

<html><head>
<title>First JavaScript lesson: Alert Boxes.</title>
<script language="JavaScript">
alert("This is an alert dialog box.");
</script></head>
<body></body></html>

Save it as *.htm or *.html, and open it in a web browser, needless to say, JavaScript must be enabled.

For your second lesson we're going to go into a slightly more advanced sort of dialog box, the prompt dialog box.

Open up notepad and type:

<html><head>
<title>Second JavaScript lesson: Prompt Boxes.</title>
<script language="JavaScript">
prompt("This is a Prompt dialog box.","This is where you get input from users");
</script></head>
<body></body></html>

Again, save as *.htm or *.html and open in a web browser.

Now for some learning. For your third lesson, we'll be taking input from a prompt dialog box and responding to it with an alert dialog box using an if, then, else loop which is a staple in any programming language.

Open up notepad and type:

<html><head>
<title>Third lesson: The if, then, else loop.</title>
<script language="JavaScript">
var input = prompt("Please type 'yes'","");
if ( input == "yes" )
{
alert("Thank you for typing 'yes'.");
}
else if (input == "no" )
{
alert("That's not what I asked for.");
}
else
{
alert("I don't understand.");
}
</script></head>
<body></body></html>

Now I'm going to break this one down as it looks a little "codey" and may be daunting to those who do not understand. First, we ask a user to type "yes" (case sensitive) and if they do, they will be greeted with "Thank you", and if they type "no" they will be greeted with a different message, for any other message or input, or any case insensitive input we didn't include an option for they program will say "I don't understand." Please note that the semicolon is not technically necessary, however it is good practice if you wish to move on to C++ where semicolons are necessary. First we declare a variable which in JavaScript is done by typing "var" and then a variable name which cannot start with, but may contain numbers. You may have noticed that when we are checking the contents of the variable we test it with an "if" statement and use two "=" signs, this is basically saying, if the variable is exactly equal to "text", then carry out the actions in the "{}", otherwise move on to the next step. Next we have an "else if" statement, which I find useful because JavaScript is kinda buggy if you use the or operator which is "||" in JavaScript, we'll get into operators later. Then there is the generalized "else" statement which is basically saying if the input did not meet the above requirements, perform this function.

Moving on to operators.

I'm only going to cover a few operators here, the basics are as follows:

Exactly equal ==
Not equal !=
Or ||
and &&

You may see these used throughout the tutorial, although the most common will be == and !=.

Now for the fourth lesson, converting strings to integers. (Used here to make a simple calculator.)

Open up notepad and type:

<html><head>
<title>Fourth lesson: Converting strings to integers for calculations.</title>
<script language="JavaScript">
var num1 = prompt("Insert first number.","");
var num2 = prompt("Insert second number.","");
var handle = prompt("Insert method of calculation.","+,-,*,/");
var answer;
if ( handle == "+")
{
answer = num1/1 + num2/1;
}
else if ( handle == "-")
{
answer = num1/1 - num2/1;
}
else if ( handle == "*" )
{
answer = num1/1 * num2/1;
}
else if ( handle == "/" )
{
answer = num1/1 / num2/1;
}
else
{
alert("I do not understand.");
}
</script></head>
<body>
<script language="JavaScript">
document.writeln(answer);
</script></body></html>

Okay, so basically what we did was divide the all the variables by 1 to make them integers and calculable, if we didn't do this, 1 + 1 would equal 11 because it would add the strings instead of the numbers. There may be a way to declare integers in JavaScript, but hey, I'm lazy and all this crap is off the top of my head. The only really new stuff here is the "document.writeln(answer);" argument, which tells JavaScript to write the variable "answer" to the HTML document. For instance if you prompted "Enter your name" and wrote that variable to the HTML document, the user's name would appear on the page.

Now for you fifth and final lesson in JavaScript (from me anyhow) we're going to learn how to get information from HTML inputs inside forms (I say from inside forms because it's easy if you have multiple forms and fields.) and use that information. And as before we're going to make a calculator, however this one will be slightly more sophisticated. I only like making calculators because it's a practical use and it's easy. This lesson will introduce you to functions and I'm sorry it may be a tad complicated to those not familiar with the concept.

The only thing you have to remember is:
Window.Document.FormName.InputName.Value.

Open up notepad and type:

<html><head>
<title>Fifth lesson: using information from forms and fields.</title>
<script language="JavaScript">
var answer;
function onplus()
{
answer = window.document.form1.firstnum.value/1 + window.document.form1.secondnum.value/1;
window.document.form1.answer.value = answer;
}
function onminus()
{
answer = window.document.form1.firstnum.value/1 - window.document.secondnum.value/1;
window.document.form1.answer.value = answer;
}
function ontimes()
{
answer = window.document.form1.firstnum.value/1 * window.document.form1.secondnum.value/1;
window.document.form1.answer.value = answer;
}
function ondivide()
{
answer = window.document.form1.firstnum.value/1 / window.document.form1.secondnum.value/1;
window.document.form1.answer.value = answer;
}
</script></head>
<body>
<form name="form1">
<input type="text" name="firstnum" value="" ><br>
<input type="text" name="secondnum" value=""><br>
<input type="text" name="answer" value=""><br>
<input type="button" name="add" value="+" onClick="onplus()";>
<input type="button" name="subtract" value="-" onClick="onminus()";><br>
<input type="button" name="multiply" value="*" onClick="ontimes()";>
<input type="button" name="divide" value="/" onClick="ondivide()";><br>
</form></body></html>

I apologize upfront for the abrupt introduction to functions. Basically a function is something that can be called upon later. There are handlers for functions they are:
onClick
onSubmit
onMouseOver
Try playing around with the various handlers for JavaScript functions (I don't recommend onSubmit for this type of app.) they basically do what the name suggests and have a variety of uses when properly coded into a JavaScript application. If you want you can add a "pi" button by using the function code:
function onpi()
{
answer = window.document.form1.firstnum.value/1 * 3.1415926535;
window.document.form1.answer.value = answer;
}

and the button code:

<input type="button" name="pime" value="Multiply first number by pi." onClick="onpi()";>

If there's any part of this tutorial you do not understand, I apologize, but in my defense, it is two in the morning. Thank you for reading this.

EDIT: Tomorrow I may update with "while", and "for" loops.

That's right, I'm back with a few more things I'd like to add to this tutorial, first I'll start with while loops. A while loop is basically declared like this:

while ( variable != other variable)
{
Do this stuff;
}

Pop open notepad and type:

<html><head>
<title>Lesson six: The while loop.</title>
<script language="JavaScript">
var key = "password";
var guess;
while ( guess != key )
{
guess = prompt("Only by typing 'password' may you continue.","");
}
</script></body</html>

As you can see, we've made an uber-basic password protected page so to speak. The while loop will continue to loop forever and ever until it gets what it wants, for example if we said var key = 1 and var guess = 1 and then declared while ( key != guess ) { alert("Fail."); } it would alert "fail" forever. Moving on to for loops.

Open up notepad and type:

<html><head>
<title>Lesson seven: For loops, making your browser count.</title>
<script language="JavaScript">
for ( i = 1; i <= 1000; i++ )
{
document.writeln(i);
}
</script></head><body>
</body></html>

When you load this page, it will display the numbers 1-1000 on the page, you can play around with the for loop on your own time.

Well I think I'm going to add relocating the browser.
Open notepad and type:

<html><head>
<title>Lesson eight: Location.href.</title>
<script language="JavaScript">
function go()
{
location.href="http://www.google.com/";
}
</script></head>
<body>
<input type="button" name="googler" value="Visit www.Google.com" onMouseOver="go()";>
</body></html>

This was an example of a simple JavaScript re-direct. You can also use a user's input to redirect them locally or anywhere on the internet using this code:

<html><head>
<title>Lesson eight-and-one-half: user defined re-direct.</title>
<script language="JavaScript">
function go()
{
location.href = window.document.form1.url.value;
}
</script></head>
<body><form name="form1">
<input type="text" name="url" value="http://">
<input type="button" name="goto" value="Visit URL" onClick="go()";>
</form></body></html>

This is an example of a simple user operated re-direct script. If you know what you're doing, you can even load web pages into different frames. I don't have an example off hand, however.
Sorry for the bump and double post, but I didn't want to open a new topic, and I can't edit that post anymore. I'm going to teach you how to manipulate CSS 'divs' using JavaScript.

Say you've got a div called "mydiv" And you want a button that will make "mydiv's" width and height change to fit different resolutions. You can do this with JavaScript.

First we must declare mydiv.

<style="text/css">
#mydiv
{
...
}
</style>
<body>
<div id="mydiv">

So now you've got a div named mydiv. How do we use JavaScript to change it's properties?

<script language="JavaScript">
function onchange(mydiv)
{
document.getElementById(mydiv).style.width = 600;
document.getElementById(mydiv).style.height = 800;
}
</script>
...
<body>
...
<input type="button" name="reschange1" value="Change size to 800x600" onClick="onchange('mydiv')";>


Here's an example page I made, try looking at the source (You need all three files.)

Save this as doit.js
Code:
function onchange(middle)
{
document.getElementById(middle).innerHTML = 
window.document.test.html.value;
}
function onbgcolor(middle)
{
document.getElementById(middle).style.backgroundColor = 
window.document.test.bgcolor.value;
}
function ontxtcolor(middle)
{
document.getElementById(middle).style.color = 
window.document.test.txtcolor.value;
}
function onheight(middle)
{
document.getElementById(middle).style.height = 
window.document.test.bgimage.value;
}
function onwidth(middle)
{
document.getElementById(middle).style.width = 
window.document.test.width.value;
}
function ontxtsze(middle)
{
document.getElementById(middle).style.fontSize = 
window.document.test.txtsze.value;
}
And the CSS:
Code:
#header {
margin-top: 0;
width: %80;
height: 30px;
border: 1px solid black;
}
#lside {
margin-top: 36px;
margin-left: 0;
float: left;
height: 400px;
width: 200px;
border: 1px solid black;
}
#middle {
margin-top: 36px;
margin-left: 250px;
height: 400px;
width: 500px;
border: 1px solid black;
}
#rside {
margin-top: -402px;
margin-right: 0;
float: right;
height: 400px;
width: 200px;
border: 1px solid black;
}
#foot { 
margin-top: 36px;
height: 30px;
width: %80;
border: 1px solid black;
}
Finally the HTML:
Code:
<html><head>
<title>Web page with everything dived up!</title>
<script language="JavaScript" src="doit.js">
</script>
<LINK REL=StyleSheet HREF="style.css" TYPE="text/css" MEDIA=screen>
</style></head><body>
<div id="header" align=center>Header</div>
<div id="lside">This is the left side div</div>
<div id="middle">Deface this website using the tools on the right, I promise I won't mind. ;)</div>
<div id="rside">
<form name="test">
<input type="text" name="html" value=""><br>
<input type="button" name="parse" value="Parse HTML" onClick="onchange('middle')";><br>

<input type="text" name="bgcolor" value="Hex (eg. 000000 = black)"><br>
<input type="button" name="bgcolordo" value="Change background color" onClick="onbgcolor('middle')";><br>
<input type="text" name="txtcolor" value=""><br>
<input type="button" name="yep" value="Change text color." onClick="ontxtcolor('middle')";><br>
<input type="text" name="txtsze" value=""><br>
<input type="button" name="textsize" value="Change text size" onClick="ontxtsze('middle')"; ><br>
<input type="text" name="bgimage" value=""><br>
<input type="button" name="changebgimage" value="Change height" onClick="onheight('middle')";><br>
<input type="text" name="width" value=""><br>
<input type="button" name="wide" value="Change width" onClick="onwidth('middle')";><br>
</form>
</div>
<div id="foot" align=center>This is the footer</div>
</body></html>
Save the HTML file as whatever you want. Save the JavaScript file as "doit.js" and save the CSS file as "style.css". This is just an example page/script. All files must be in the same folder unless told so by the "src="..."" and the "LINK REL..." things.

Basically by using getElementById(element) you can use several different CSS options by defining them with JavaScript, in the example page, it's all user defined, however.
Nice, I have learnd some stuff using this tut
Here is an interesting way to keep things out of your history. Don't know quite how it works, but I guess since your browser is only technically viewing one page, it doesn't look at the pages you're viewing inside the page. I'll explain.

Using the "<object>" tag, you can insert a web-page into a div, still trying to figure out if you can manipulate this with JavaScript, but anyway, try this basic concept.

Make a div.

<style type="text/css">
#dontlook
{
width: 600;
height: 700;
}
</style>
....
<body>
<div id="dontlook"><object data="http://www.google.com/"></object></div>
...

Now I recommend setting the data to google because I don't know how to manually manipulate it, and using google you can search for a website and visit it. Now, clear your history, and try going to MPGH.net through the embeded google page. Check your history. There is none. Not google, not MPGH. Now, try visiting Google in a new tabdow. Check your history. It will say Google.com.


Interesting...

Edit: FIXED!

I made a page that will allow you to navigate using a simple text input and a button. Now you can use these tools to browse the web without leaving a footprint in your history.

Source:
Code:
<html><head>
<title>That's right.</title>
<script language="JavaScript">
function onurl(gonow)
{
document.getElementById(gonow).innerHTML = "<object data='" + window.document.form1.url.value + "' width=800 height=800>";
}
</script>
<style type="text/css">
#gonow
{
width: 800;
height: 800;
border: 2px solid black;
} 
</style></head><body>
<body>
<form name="form1">
<input type="text" name="url" value="http://">
<input type="button" name="go" value="Visit URL" onClick="onurl('gonow')";>
</form><div id="gonow"></div>
</body></html>
Edit: Just found out you have to copy/paste every link into the text area for this to work properly... =/
Sorry about the double post, but I can't edit from a day ago. I added the three files (*.html,*.js,*.css) into a *.rar archive. Minor changes, more options, different look. Enjoy.

Well, since I already posted, it may as well be useful. Plugging into JavaScript from links. Say you wanted to make a link and when a user clicked on said link, it did something in JavaScript. There are two ways to do aforementioned "thing." First would be to write a function and call it by way of a handler through a link.

Open notepad and type:
<html><head>
<title>JavaScript link.</title>
<script language="JavaScript">
function alert()
{
alert("I like pie");
}
</script></head><body>
<a href="#" onClick="alert()";>Link text.</a>
</body></html>

And the above code should create an alert box when it is clicked.

The second way to call onto JavaScript by way of a link would be using the link to directly plug into JavaScript functions. For example, if we opened up the attachment and in the text field above "Parse HTML" and typed: <a href="javascript:alert('I like pie.');">Link text</a> We would have effectively achieved the same thing.


Challenge: Change all buttons on the test page into links.
Reward: You know HTML and basic JavaScript, continue your learning.
Side note: Put this code in the "Parse HTML" text input:
<a href="javascript:function onchange(header){document.getElementById(header).i nnerHTML='OMGWTFBBQ';}" onClick="onchange('header')";>This is a link (Yes it is.)</a> It's very...strange...
test.rarattachment deleted · 3 downloads before removal
Posts 15 of 5 · Page 1 of 1

Post a Reply

Similar Threads

Tags for this Thread

Need help?