Who is online?
In total there is 1 user online :: 0 Registered, 0 Hidden and 1 Guest

None

[ View the whole list ]


Most users ever online was 9 on Sun Jul 09, 2017 2:04 am
Statistics
We have 15 registered users
The newest registered user is bilde

Our users have posted a total of 271 messages in 27 subjects
deleted after updated

Basic Javascript: Lesson 1 - Getting Started

View previous topic View next topic Go down

Basic Javascript: Lesson 1 - Getting Started

Post by Admin on Fri Dec 02, 2011 12:38 pm

As you all know (or should know) this forum is about learning rather than just taking. Those of you that are interested in learning, i hope this section can be an invaluable resource in helping you learn Javascript.

This first lesson will be a short sweet introduction to Javascript, and we will be starting from the very beginning. Smile

Please be aware that for these lessons I will be assuming you have a bit of HTML knowledge, and will not be teaching HTML in these lessons. It is almost essential to know a bit about HTML before learning Javascript, so if you don't feel comfortable with HTML i suggest you take the step to learn it before venturing through these lessons.

Throughout the lessons i will be providing snippets of code to demonstrate and even some working examples.

Contents of this lesson
- The script tag, starting a javascript.
- Inline scripts & JS files.
- Variables and Strings
- Basic User Input.
- The famous IF - ELSE statements.

The Script Tag, Starting a Javascript
I'm sure you will have seen this in places around forumotion. The Script tag, is a HTML tag which signifies the start of a script, most commonly a Javascript. Like most HTML tags it needs to be opened and then closed.

So here's the regular script tag you'll see everywhere:
Code:

<script type="text/javascript">
Javascript Here
</script>
The 'type' attribute simply specifies that the script within the tags is Javascript. This attribute is not often needed nowadays as pretty much every browser will assume Javascript, however it should be used for safety.

Sometimes the script tag isn't needed however.

Inline scripts & JS files.
When using the script tag amongst the HTML of your pages, this is called an Inline Script. Its likely named this due to the fact it is inline with the rest of the HTML. The script tag is used to signify the start of a script.

When you have Javascript written within a javascript file, the script tag is not needed. Why? Because it's in a Javascript file and so there is no need to signify that it is Javascript. Javascript files end in '.js' (for example 'myjavascript.js').
To load your javascript file into your HTML page, you must use the script tag but this time with the source attribute so specify the source of the Javascript file.
Code:

<script src="/myjavascript.js"></script>

Now that you know how to include Javascript in your pages, lets begin to learn the language Smile

Variables and Strings
In my opinion Variables and Strings are the two things you will use most in Javascript.

Variables
Variables hold information. The information a variable can hold is almost endless in possiblities, it can hold text, numbers, HTML elements, objects and more. We use variables in Javascript to store information so we can refer back to it and use it later on. The start if a new Variable is signified by using the word 'var' in Javascript.

So here is an example of some variables. Please read through the code below, and read my comments within it.
Code:

<script type="text/javascript">
var x=1;
var y=2;
//a variable called 'x' now holds the value of 1, and a variable called 'y' holds a value of 2.
//at this point i should say, all lines of javascript end in a semi-colon.

var z=x+y;
//variable z will hold the value of 3. Because 1+2 is 3 obviously.
</script>

So that showed you examples of variables holding a number value. Now we're going to take a look at strings.

Strings
Strings are a Javascript object. A string is just text. Not much more to say haha.
Strings can be started by either a Quote mark or a double quote mark, and they must be ended with whatever quote mark they started with. By this i mean, if you start a string with a double quote mark, then you must end it with a double quote mark, and within the string you can use as many single quote marks as you want and it won't end your string.

Here are some examples of variables holding string values:
Code:

<script type="text/javascript">
var x="Hello";
var y="There";
//variable x holds 'Hello' and variable y holds 'there'.

var z=x+y;
//variable z at this point would hold 'HelloThere'
//To mae this better we must insert a space somewhere within our strings.
//Here are three different ways to do this:

var z=x + " " + y;    //this is now x plus a string which is just a single space plus y. or
var y=" There";      //we could have had a space at the beggining of the string in y. or
var x="Hello ";      //we could have had a space at the end of x
</script>

Now that you know about simple variables. Its time to see a small use for these variables in a live example. First, you will see a new piece of Javascript on the example page, called an 'Alert Box'.
Alert boxes put an alert box up on the page to the user.
You use an alert box like this:
Code:
alert('Hello There');

Within the brackets of course, is what you want the alert box to say.

So here is your first live example of a small piece of javascript:

The code used in this example should be pretty clear to you but since its our first example i will explain it:
Code:

<script type="text/javascript">
var x="Hello ";
var y="and welcome!";
alert(x+y);
</script>

I'm ignoring the script tags, so when i refer to the first line, i mean the first line within the script tags. In this case: 'var x="Hello ";' and this will be the case throughout the lessons.

Anyway the first line of course specifies a variable called 'x' which holds a string with value of 'Hello '.
In the second line you can see another variable called 'y', which holds another string.

Now the interesting new part. The alert box.
You'll see that within the brackets of the alert box, i have not put any text. Instead i have put 'x+y' meaning that the alert box will alert the value of x=y, which is of course 'Hello and welcome!'.

So hopefully that covers the basics of strings for you. Later on in a later lesson we will return to strings and talk more about how to manipulate them and use them more to our advantage. We're now going to move on to some ways to get input from the user.

Basic User Input
So far you have learnt about, how to start a Javascript, Variables, Strings, And an Alert Box.
In this section your going to learn about the Prompt Box, Confirm Box, and an extra bit, not related to user input 'document.write();'

So to start this section, take a look at your next live example. After viewing the page, right click and view source and you'll see the script.
I've combined all the things we'll be looking at in this chapter into the one page.

So here it is: http://lgforum.forumotion.co.uk/h3-

So if you have clicked 'View Source' then you will have seen this:

Code:

<script type="text/javascript">
var x=prompt('Hi There. What is your name?','Name here');
var y=confirm('Hi '+x+' and do you want a welcome message?');

if (y) {
  document.write('Welcome '+x);
}
else
{
  document.write('Well here is a welcome anyway!');
}
</script>

So the first bit of this, is a variable named 'x' and what you see within that variable is something new called a Prompt Box.
You have seen how the prompt box works, as it was the first box you saw on the example page. The 'Prompt' function has two parameters, the first is what you want the prompt box to say, the second is what you want the default value to be.
So as you saw our prompt box was: prompt('Hi There. What is your name?','Name here');
The first bit within the brackets being the first parameter, and the bit after the comma is the second parameter. The second parameter is optional and can be left out. Once the user has typed something into the prompt box, the variable holds the value. So as i typed in 'LGforum' to the prompt box, the variable x, held a string with the value of 'LGforum'.

The next line shows a variable called 'y'. You'll see in this variable something new again, the confirm box. This is similar to the prompt box, however it does not provide a text field for the user to type in, instead it provides an 'Ok' button and a 'Cancel' button. If the user is to press the Ok button then variable 'y' holds the boolean (meaning true or false) value of true. And if they click cancel then it equals false. You can see that i have added the value of 'x' within the confirm box parameter to contain whatever the user typed in the first box.

This should hopefully be quite clear for you, so we're going to jump straight to the next chapter to learn about the next bit in the code. The IF statement.
Here is more info about the pop up boxes we've looked at: http://www.w3schools.com/js/js_popup.asp

The Famouse IF-ELSE Statement
IF statements are used very often in Javascript. They are used to run a piece of javascript depending on certain factors. For instance, in the example you saw that it will give you a welcome if you chose to have it. If you chose not to have it, it gave you a different welcome message.

The way to use the IF statement is simple. This is how it is laid out:
Code:

if (condition) { do this }
The word 'if' obviously signifies the start of the 'if' statement.
The part within the brackets is the condition to test.

This can be a lot of things. Here are some examples:
Code:

var x=1;
var y=2;

if (y == 2) { //this statement is true and so will run the code }
if (x < y) {  //this statement is true }
if (x == 2) { //this is false and so the code will not run }
if (x) { //this is true, due to the fact x has a value. If x didnt have a value, or had a value of false then it would be false }
if (y+x == 3) { //this is of course true }
SO there you have some examples. You have seen once again that variable can be used within the condition. Variables can be used in almost everyway in Javascript.
I'm going to quickly run through the example conditions i showed you:
The first one checks 'if y equals 2' which is of course true and so the code within the curly brackets will be executed.
I should explain that '==' is how we say 'equals' in Javascript. And on a similar note '&&' is how we say 'and', and '||' is how we say 'or'.
The rest of the conditions should be pretty clear to you.

Here are some more:
(i've removed the actual 'if' word and curly brackets bit for quickness)

(y==2 || x==2) - means if y equals 2 or x equals 2.
(y==2 && x==2) - means if y equals 2 and x equals 2.
(x || y) - means if x or y has a boolean value of true.

The Else Statement.
The else statement comes after an IF statement, as the code to execute if the condition is false. So if the condition is false, then it will not run the code in the curly brackets after the IF, but will instead run the code in the curly brackets after the ELSE.

Look back at the example page and code now, to take in a full understanding or how this works.

If you have fully understood everything and you are comfortable to move on, then i have a task for you to try out. After all, experimenting and trying things is a good way to learn.

Task Number 1
With all the information in this lesson you should be able to write a script which when the page loads, it asks the user to type in a letter. Then check if the letter is a vowel or not. If it is a vowel, alert a box saying it is a vowel, if it isn't alert a box telling the user that it isn't a vowel.

If you have managed to do this or tried a lot. Here is a script that will do the following, but don't look at this until you have tried:
Spoiler:

<script type="text/javascript">
var x=prompt('Please enter a letter','Any letter will do');
if (x=='a' || x=='e' || x=='i' || x=='o' || x=='u' ) { alert(x +' is a vowel!'); }
else { alert(x + ' is not a vowel'); }
</script>

This can be done in quicker ways. But of course i only used what we have learnt so far.
If your solution was different, please feel free to share it as a post to this thread.
avatar
Admin
Admin

Avacweb
Posts : 231
Points : 282
Join date : 2011-11-07

View user profile http://testlg.forumotion.co.uk

Back to top Go down

Basic Javascript: Lesson 2 - String Manipulation And Uses

Post by Admin on Tue Dec 06, 2011 8:18 am

Welcome to your second lesson in beginner Javascript. I hope you tried out the task at the end of the last lesson, and if you succeeded then you are ready to move on Smile

In the first lesson we looked at starting a javascript, and then began to move on to a few of the first things you should know.
- You should be comfortable knowing what a Variable is, and how to make one.
- You should know how to bring up an Alert, Prompt and Confirm box.
- You should be able to use an IF-ELSE statement.

In this lesson we are going to be looking deeply at String Manipulation. By this i mean, manipulating strings (if you remember what a string is Wink ) to do certain things or to get certain information from them. Here are our five subjects for this lesson:
- Finding the length of a string.
- Finding the position of character in a string.
- Finding the character at a position in a string.
- Splitting a string.
- Taking parts of a string out.

First of all i will refresh your memory. A String is text and most often is stored in a variable. Example:
Code:
var x="hello";
The variable 'x' now holds the string 'hello'

Okay so lets begin Smile

Finding the length of a string
A string is an Object. And Objects all have methods and properties. It may be all confusing Javascript Jargon at this stage, but i assure you it will come clear one day. In this lessons you will be learning some of the common methods and properties of the string object.

A string object, has a length property. But i'll stop jibbering and show you how it is done.

Code:

var x="hello";
var y=x.length;
The variable 'y' here, holds a number value, which is of course the length of the 'x' variable. Which in this case is 5.
Easy huh?

Now lets think of some sort of practical implementation. We'll revert back to lesson 1, where we talked about prompt boxes. Lets say we ask the user their name again via a prompt box. They may enter a space, or just one letter which clearly isn't their name.
So take a look at this:

Code:

var x=prompt('Please enter your name');
if (x.length < 3) {
    alert('surely that isn't your name?');
}

This bit of code prompts the user for them to type in a name. It then has the IF statement we talked about at the end of the last lesson. The condition of this statement is if the length of x is less than 3. I.E, if what the user has typed in is less than 3 letters long. I'm going to assume that the contents of the IF statement is pretty clear to you since we went over it before.

I'm hoping this '.length' thing is pretty simple to you. So we'll move on and use it with other things too Smile

Finding the position of character in a string.
In this chapter, your going to learn about index number's. These become very important in Javascript and are used a lot.
An index number is just a position. If there are more than one of the same thing then they can be accessed by their Index number. One important thing to remember is that index numbering starts at '0'. So the first instance of something is at position '0', and the second is '1' and so on.
A good way to explain this in terms of your forums is, on a topic page, each post has the class name of 'post' and of course there is more than one on the page. The first post would be post 0, the second post would be post 1 etc...

Okay so since we are talking about strings, you may be wondering 'well where do index's play a part?'.
The answer is the characters of a string. The first character is at position '0', the second character is at position '1' and so on.

So how do i go about using this in strings. Well a little function called 'IndexOf' will find you the index number of a character in a string. Here is quick example:
Code:

var x="Hello!";
var y=x.indexOf('H');

So you'll see here, that 'x' holds the string 'Hello', this should be dug into your mind by now.
The variable y is where we use indexOf. Just like the length property we learnt in the last step, we put 'x.' before it. This 'in x'. So its like saying 'in x check the length' or 'in x check the index of'. So in this example you'll see indexOf and then in the brackets the single letter string of 'H'.

If you hadn't guessed it, this wil check where 'H' is inside of 'x'. Once found (if found), 'y' will then equal the index number where 'H' is. Which in the word 'Hello!' it is at the position of 0, so 'y' now equals 0. I hope that makes sense. If we were to do: y=x.indexOf('o')
Then 'y' would equal 4. It equals 4, because of the first letter being 0, so the 5th letter is index 4.

Okay so what happens if the string you check the indexOf can't be found in the string? Well the indexOf function will return the value of -1. Let me show you what i mean:

Code:

var x="Hello!";
var y=x.indexOf('K');

In this instance, 'y' would equal -1, because the index of K in 'Hello!' does not exist. Your probably thinking, 'but why would you search for a letter that does not exist?' ...Well, let me show you an example of a possible real life situation. Now this code, is a combination of things we have learnt so far, but if you read through it slowly you should understand it all.
Remember to read the comments in the script.

Code:

var x=prompt('Please enter your email address.');  //asking the user for their email address
var y=x.indexOf('@');                                      //Checking for an '@' sign within the variable x.
if (y == -1) {                                                //if y is -1, meaning if it found no '@' sign in variable x.
alert('Please enter a valid email address');          //the email address can't valid if it doesn't contain an @ sign.
}                           

Okay, so hopefully you understand all that. That shows a good use of the 'indexOf' method.
Before we move on to our next chapter, i'd like to point out that 'indexOf' can be used for more than just single letters. You can search for whole words within sentences. Here are some examples for you:

Code:

var x="Hi there, welcome to the site!";
x.indexOf('there');    //this would return the number 3. Because thats where 'there' starts.
x.indexOf('t');          //this would also return 3. t takes the index of the first instance of 't'.
x.indexOf('me');        //although the string doesn't contain the word me, 'me' is included in 'welcome' and so would equal 10.

I think we're ready to move on to our next string manipulation method.


- Finding the character at a position in a string.
Now this chapter should be very easy for you, as it is very similar to indexOf. However this time we are working the other way round. Instead of looking for a string within a string, we're actually looking at a position in a string, and it will return the letter at that position.

using the 'charAt' method, we can return the character at a position in a string. So we'll just jump straight to an example, as I guarantee you'll find this simple Smile

Code:

var x="Hi there!";        //a simple string in variable x, like you've seen a lot now.
var y=x.charAt(0);      //so this is now asking for the character at position '0' in x. Which is 'H' of course.
var z=x.charAt(x.length-1);  //now here is something strange. I''ll explain this to you below.

Okay then, i'm gathering that you understood the .charAt function due to its similarity to the 'indexOf' method, and since we have already covered index numbers.
Right, so its time to explain the last line of that snippet, the variable 'z'.

As did the second line, the last line uses charAt, and it is looking within 'x'. If we take a look inside the charAt you'll see this 'x.length-1'
You know what x.length means, and you know that it will return the number of 9 in this case. As the length of x is 9. You'll also see that i have put '-1' after it, changing the total to 8. So have you guessed it yet? This line is returning the last character in the string! Smile
The first character being at index 0, the second being at index 1, so the 9th character is at index 8. Which is 'x.length-1', neat eh?

avatar
Admin
Admin

Avacweb
Posts : 231
Points : 282
Join date : 2011-11-07

View user profile http://testlg.forumotion.co.uk

Back to top Go down

View previous topic View next topic Back to top

- Similar topics

 
Permissions in this forum:
You cannot reply to topics in this forum