QuickRead 16: JavaScript Part 2
| Alerting and Prompting | ||||||||||||||||||||
That little box that came up was an example of an alert box. The code
that did that is pretty simple.
<script>
alert ("This is an alert box");
</script>
Thats it. You can also use variables by not using ". Also, the + works as it did for
document.writeln so you can do something like:
<script>
var blah="I am a variable";
alert ("blah is " + blah);
</script>
Now comes something that can be really powerful, you can recieve user input using JavaScript. Here is the command to pop up a prompt for the user to type in (from now on we will assume you put the code between <script> and </script> tags): var rooting = prompt("Who are you rooting for?", "Pacers"); This will pop up a prompt window that asks the question "Who are you rooting for?" In addition, it has the word Pacers (the thing in " after the ,) already filled out in the form. This is called a default answers, because the question defaults to this answer if the user doesn't change it. When a user hits the ok button, whatever they typed in gets assigned to the (newly declared) variable called rooting. We can now print this variable or do stuff with it. You can also assign the prompt function to a previously existing variable (one that you already declared using var). document.writeln("I think the " + rooting + " kick but too!"); if the user were to input say, "Blazers" our little JavaScript would print "I think the Blazers kick but too!" Here's a prompting example. And this is the code that did that:
var emotion = prompt("How do you feel today?","");
document.writeln("I understand you are feeling " + emotion + " today");
It asked the question with prompt, assigned whatever the user typed to emotion, then printed it out
using document.writeln. There is no default answer because there is nothing between the " after the
comma.
| ||||||||||||||||||||
.
| .
| The conditional statement
| One of the fundamental building blocks of any programming language is the
"if" statement. It goes something like this: | if (some condition) { first section JavaScript commands maybe some more commands ... } else { second section more stuff ... } The part of the statement in the () is called the conditional part. If the conditional is true then the commands in the first section { } are used. If the conditional is not true then the second section { } is used instead. You don't have to have the else { ... } (ie the second section) if you don't want JavaScript to do anything when the conditional is false (not true). There are several things that you can test for "trueness". The most basic is equality, that is are two things equivalent. You do this with TWO equal signs == For example: if (userinput == 345) { document.writeln("You input was 345, I like that number"); } here, if the variable userinput holds a value of 345, the conditional part of the if statement evaluates to true and the statement(s) within the braces are executed (there isn't an else part on this example). If the variable userinput wasn't 345 then it wouldn't have printed anything. Be very careful with testing equality because if you use a single =, then you will confuse the browser into thinking you actually meant to assign the value 345 to a variable called userinput. Now userinput would have the value of 345. It would be considered true by the way. You can use not equal (!=), less than (<), greater than (>), less than or equal to (<=) and greater than or equal to (>=) for your conditionals. Here's another example: if (rooting == "Pacers") { document.writeln("Pacers are going to win the NBA championship"); } Notice that when we were comparing the equivalence to a string, we had to enclose it in quotes. This is very important (without the quotes it would have compared the value of the variable rooting with the value of the variable Pacers). You can more than 1 part to the conditional. For example, if you want some statements to be executed if some variable satisfies either of two conditions, you would use the double pipe symbol (the pipe symbol is above the \ character on the key pad. A "double pipe," is simply two pipe symbols). Here's how: if (userinput == "yes" || userinput == "Yes") { do this; } This is true if the value of userinput is the word yes OR the word Yes (capitalization matters). When you want two conditions to hold on an "if" statement simultaneously, you would use the double ampersand or the && symbol. Here's how: if (userinput < 200 && userinput > 100) { do this; } This is true if the value of userinput is less than 200 AND greater than 100. Remember that userinput is just a label for a box, JavaScript doesn't get anything input from the user without a prompt command, no matter what you name the variable. .
| .
| Mouse over, out, and click events.
| JavaScript has the ability to respond to things the mouse does on a
page. For instance, it could recognize the mouse going over a picture, or clicking on a word. This
type of JavaScript code does NOT go between <script> and </script> tags. It goes inside
of an 'a' tag as in <a href=....>.
| The first event we will discuss is onMouseOver which activiates when the mouse is over the stuff between the <a href=..> and </a>. For example, consider a normal link like: A link with this code: <a href="http://grove.ufl.edu/~u3063bnk"> A link </a> In this case the words "A link" are what the mouse pointer has to pass over. Anywhere you could have a link you can have one of these mouse events. This example is going to change 1 picture to another picture when the mouse goves it. The two pictures need to be about the same size, or second picture will get squished or expanded to fit the space that the first one took for the other. Here's the example: Bring your mouse over this rather large picture and it will change from a purple picture of a flower to a green one.
You'd be surprised to see the code that did that as it is pretty short: <a href="#" onMouseOver="document.pic.src='green.jpg';"> <img src=purple.jpg name=pic border=0> </a> What was that all about? This is pretty much like a link where a picture is the item that activates the link. The picture is our regular <img> tag with its src attribute. However, we added a new attribute called name. Just like we named frames (remember we name frames when we create them), we name pictures when we post them and want to later change them (in this case by substituting another picture). We set the border to 0 so that it doesn't look like a link, this is for aesthetical reasons only and doesn't affect the JavaScript. We use the image as a link but the link is bogus as it is just a "#." The real key is inside the <a> tag. The normal href attribute is there but so is this new onMouseOver thingy. That is the JavaScript. onMouseOver (notice that the M and the O are capitalized, you have to stick to this or your event will not work!) is of the form: onMouseOver=" javascript code here; " The quotes ARE important! The onMouseOver code is activated when the mouse goes over the picture (because the picture is within the <a..> and </a> tags). In our example, JavaScript looks at the document (the name for the page that is being displayed) and then looks for something that has been named pic. It finds the <img> tag that has name=pic. Now for that thing it found named pic (our <img > tag) it finds the attribute named src and changes it to 'green.jpg'. Notice that within double " you use single '. If you used " around the picture name JavaScript would think that was the end of the onMouseOver event and get confused. Also, don't forget the semicolon ; before the closing ". This changes the thing named pic's part named src. So now instead of using purple.jpg as the filename for the picture it uses green.jpg and thus the picture has changed. JavaScript can change the attributes of most things that are named, but it usually can't change the size (width, height, or size attributes) of anything. Make sure you don't have two things with the same name or JavaScript won't know which is which. You can have more than one statement inside the quotes but unless it's absolutely necessary, it's better programming style to put your code at the beginning in a method (a method is a collection of code that does a specific task, we won't be writing methods in this class, also called functions in other languages). This event was activated when the mouse came over the picture, what if you want the other way around, that is when the mouse is no longer over the picture? This is actually extremely similar: <a href="#" onMouseOut="document.outpic.src='green.jpg';"> <img src=purple.jpg name=outpic border=0> </a> Even more common is to combine these two, so that you do something when the mouse comes over the picture and then do something else when the mouse leaves the picture. Like flip the picture back and forth. <a href="#" onMouseOver="some code..;" onMouseOut="some other code...;"> <img src=purple.jpg name=outpic border=0> </a> The code that does the blue and orange balls on the main page use this. It switches the picture from orange to blue (we have two pictures one is orange the other is blue) when the mouse is over the link, and then switches from blue to orange when the mouse leaves. You can take a look at the code but there is some other stuff in there also (we used a 'method' as well as preloaded the pictures for speed). Next, we will look at how to respond to the mouse clicking on something. Here's the code that takes care of mouse click events: <a href="#" onClick="document.clickpic.src='green.jpg';"> <img src=purple.jpg name=clickpic border=0> </a> Yep, just substitute onMouseOver with onClick. These events can do other things besides changing pictures. For instance, Click me. This time our onClick event called an alert. Here is the code: <a href="#clickalert" onClick="alert ('You clicked me');">Click me</a> Since this was a link, the browser will go to whatever is in the href part. I used a <a name=clickalert> tag just above this paragraph so clicking on that link to you to that part of this document (see Quickread 6 for details on linking within a single web page). There are ways around that, but we won't go into them. You can just use href="#" but understand that clicking on it will take you to the top of the page after the alert comes up. .
| .
| Some Important Miscellaneous Notes
| First a warning about Javascript and names (for pictures, frames or
other things): if you have JavaScript code defined on more than one picture, at different
places in your document, you will need to use different variable names for the pictures.
Notice the usage of the names "pic", "outpic", and "clickpic" in the examples). If you are
using onMouseOver and onMouseOut on the SAME picture then you will use the same name. The
idea is to not confuse the browser into not knowing which picture you are referring to.
| This was mentioned in Part 1 but is worth repeating. Beware of line wrapping (when you get to the end of a line in pico the text goes to the next line). DO NOT line wrap within the ". For example, this won't work <a href="#" onMouseOver="some really ............... long code"> Because the ending " for onMouseOver is on a different line then the starting ". If you use both onMouseOver and onMouseOut, they can be on separate lines. This also applies to all elements that have quotes between the <script> and </script> tags. As always, come see us if you are having problems. If you aren't within " or ' and you have a space, then you can probably go to the next line there. If you declare a variable (with var, say for your prompt) then your other references to that variable need to be inside the same <script> .. </script> section or JavaScript might 'forget' what the variable was. Between the <script> and </script> tags you can only use your JavaScript code. If you put regular HTML tags in there, JavaScript will think they are commands and will crash. .
| .
| This stuff is kinda neat, any more?
| There is a lot more that Javascript can do that we don't have time
to talk about. It can open up extra windows, read stuff about the user, change the status
bar, do calculations, adjust form elements, error messages, change links, change text, and
many other things. If you are interested, search the web for a "Javascript Tutorial" near you,
there are many out there. A few that look good to us:
|
.
| .
| Get behind the wheel!
| Type out the following JavaScript and see what
it does: | <html> <head><title>JavaScript</title> <script> var name = prompt("Thanks for coming to my homepage, what's your name?",""); alert("Hi " + name + ", I hope you'll enjoy what I've done here"); if (name == "mark" || name == "Mark") { document.writeln("<font color=red>" + name + " where's the money you owe me!! </font>"); } else { document.writeln("<font color=red>" + name + " is the greatest person to walk this earth! </font>"); } </script> </head> <body> This is the body. Don't forget to not let things line wrap if you cut and paste this into the box below. </body> </html> .
| |
| Index |
| 12 | 15 | 16 | 17 | 18 |