Class Notes


Javascript

  1. Javascript Variables & Variable Concatenation
  2. Javascript Functions
  3. Rollovers
  4. Javascript innerHTML
  5. Javascript Timeouts
  6. Javascript Intervals



Javascript Variables & Variable concatenation

Concatenation: the operation of joining two or more character strings end to end.

To join two strings together, we use the + (plus) symbol.
<head>
      <script type="text/javascript">
            var name = "John" + "Doe";
            alert(name);
      </script>
</head>

This will alert "JohnDoe".

It's a little pointless to concatenate to non-variable strings together, as you could just do this:
var name = "John Doe";

Usually concatenation is used when you have variables:
var first = "John";
var last = "Doe";
var name = first + " " + last;
alert(name);
This will echo "John Doe";


You can also add strings to the end of a variable with "+=":
var sentence = "John Doe";
var sentence += " is so awesome!";
alert(sentence);

This will echo "John Doe is so awesome!";


Functions

Description:

A function contains code that can be executed by an event or by a call to the function. Functions are often used when you need to do something more than once, with the same or similar results.


The Code:

<head>
      <script type="text/javascript">
            function myAlert(msg) {
                  alert(msg);
            }
      </script>
</head>

<body>
      <a href="#" onmouseup="myAlert('test');">Alert "test"</a><br />
      <a href="#" onmouseup="myAlert('pizza');">Alert "pizza"</a>
</body>

Example:

Alert "test"
Alert "pizza"

Explanation:

First we create a javascript function called "myAlert" (you can call it whatever you'd like).
A function always starts with "function", then a space, then the name of the function.

After the function name, you must always have an open and closed parenthasis.
Although you don't NEED anything in the parenthasis, in this case, we'd like to pass our function a variable. To do so, we must include the name of our variable between the open and closed parenthasis. Our variable is called "msg".

After the parenthasis, we "open" the function with a "{" and close it with "}" (without the quotation marks).
Everything between the { and the } is the contents of the function and will be run when the function is called.

We then create two links, which call the "myAlert" function.
To call a function, you must use the function name, and an open and closed parenthasis.

Within the parenthasis, you must match the number of variables the function "calls for". In this case, our function requires one variable (because we put one thing inside the parenthasis when we created our function.

So, to call our function, we use: myAlert("something")

When javascript reads this code, it will run the contents of our function, and replace msg with "something".

So, for our example, the first link will alert "test", and the second will alert "pizza".

Javascript Rollover

A rollover is a screen event that occurs when the mouse is moved over an area of a web page. One way to create this effect is by using Javascript.

Here are my two images:
square design 1    square design 2

The Code:

<head>
      <script type="text/javascript">
                  upimage = new Image(100, 100);
                  upimage.src = "images/tile1.gif"

                  downimage = new Image(100, 100);
                  downimage.src = "images/tile2.jpg";
      </script>
</head>

<body>
<a href="http://www.bgsu.edu"
onmouseover="document.square.src = downimage.src;"
onmouseout="document.square.src = upimage.src;">
<img src="images/tile1.gif" width="100" height="100" border="1" name="square">
</a>
</body>

The Example:


Javascript - innerHTML

Description:

innerHTML references the html inside of an element

The Code:

<head>
      <script type="text/javascript">
            function changeContents(msg) {
                  document.getElementById('myDiv').innerHTML = msg;
            }
      </script>
</head>

<body>
      <a href="#" onmouseup="changeContents('test');">Changes the content to "test"</a><br />
      <a href="#" onmouseup="changeContents('pizza');">Changes the content to "pizza"</a>


      <div id="myDiv">
            Contents of my div.
      </div>
</body>

Example

Changes the content to "test"

Changes the content to "pizza"

Contents of my div.



Appear or Disappear using Javascript


The Code


<head>
      <script type="text/javascript">

            function hide(elem) {
                  document.getElementById(elem).style.display = "none";
            }

            function show(elem) {
                  document.getElementById(elem).style.display = "block";
            }

      </script>
</head>

<body>
      <a href="javascript: hide('myDiv');">Hide</a>
      <a href="javascript: show('myDiv');">Show</a><br /><br />

      <div id="myDiv" style="height:100px; width:100px; background-color:#990000;"></div>
</body>



Code in Action


Hide   Show



Explanation

With CSS, we can change the "display" of an element. Setting "display:none;" would make a div disappear. Setting "display:block;", while not necessarily intended to make something appear, WILL make it appear if it was previously set to "display:none;".

But - if we want it to disappear or reappear on the fly, we need to use Javascript. Luckily, Javascript allows us to change CSS.

In the example above, we have 2 links. The first calls a Javascript function that tells our object to change it's CSS to "display:none;". (You'll notice, setting CSS via Javascript looks a bit different than setting it in CSS.) The second does the same thing, but sets the display to "block" instead.

In-class Exercise

You do not have to just make a single DIV or IMG appear/disappear - what if you made a div with a bunch of things in it, then made that container DIV display appear/disappear?

Part 1 (the setup):
  1. Create a <div> with id="container" (don't forget to add a close </div> as well)
  2. Set it's height and width with CSS to 500px wide and 400px tall
  3. Set it's background-color to #CCC
  4. Center it using margins: margin: 50px auto; /* This will move it 50px from the top, and set it's left and right margins to "auto", which will center the div */
  5. Create two divs inside of the "container", and give each one an id of your choosing, and set them to 50px wide by 50px tall.

Part 2:
  1. Set the container box to position:relative;
  2. Set the position of the small inside-boxes to to position:absolute;
  3. Change the top or bottom and left or right properties of the inside boxes to position them around inside the container box.
  4. Try setting some to negative pixels: top: -25px; for example - what happens when you set them to negative pixels?

Part 3:
  1. Use the code above to show/hide the container box - you should notice that it shows/hides the boxes inside of it as well!
  2. Try making the container or one of the inner boxes disappear when you rollover something on the page and reappear when you roll outside of it.


How could you use this in your project? What other applications could it have?

Check out: http://www.w3schools.com/CSS/css_examples.asp



 

Timeouts

Description:

A "timeout" is like setting a kitchen timer and telling it to do something specific when it's time runs out.

The Code:

<head>
      <script type="text/javascript">
            function delayedAlert() {
                  setTimeout('alert("TESTING")', 3000);
            }
      </script>
</head>

<body>
      <a href="#" onmouseup="delayedAlert();">Delayed Alert on Mouse Up (click)</a>
</body>

Example:

Delayed Alert on Mouse Up (click)

Explanation:

The mouseup event calls the "delayedAlert" function and this starts the javascript timeout with "setTimeout", and passes two variables - the first is what you'd like to run, and the second is time (in milliseconds) before it should run.

In this case, we have it call an alert (with "TESTING" as it's alert text), and we tell it to wait 3 seconds (3000 milliseconds) before it calls it.

Example of a simple timer for the page:

<html> <head> <script type="text/javascript"> function clock(){ var time1=setTimeout("document.getElementById('theTime').innerHTML='2 seconds'",2000); var time2=setTimeout("document.getElementById('theTime').innerHTML='4 seconds'",4000); var time3=setTimeout("document.getElementById('theTime').innerHTML='6 seconds'",6000); var time4=setTimeout("document.getElementById('theTime').innerHTML='8 seconds'",8000); var time5=setTimeout("document.getElementById('theTime').innerHTML='10 seconds'",10000); } </script> </head> <body> <p><a href="#" onclick="clock()" />Click here to start</a></p> <div id="theTime">0 seconds</div> <p>The clock will tell you when two, four, and six seconds have passed.</p> </body> </html>




Intervals

Description:

A "interval" simliar to a "timeout", but it continues to run until specifically told to stop.

The Code:

<head>
      <script type="text/javascript">
            var myInterval = "";
            function continuousAlert() {
                  clearInterval(myInterval);
                  setInterval('alert("TESTING")', 4000);
            }

            function stopAlert() {
                  clearInterval(myInterval);
                  alert("Continuous alert has been stopped");
            }

      </script>
</head>

<body>
      <a href="#" onmouseup="continuousAlert();">Start Continuous Alert</a>

      <a href="#incode_intervals" onmouseup="stopAlert();">Stop the Alert</a>
</body>


Example:

Start Continuous Alert

Stop the Alert

Explanation:

First, we create a link, and give it an onmouseup state, which is triggered when the mouse button is let "up" (a click). (You can use any mouse event, we're just using mouseup as an example).

Then, we create a function to be called when the mouseup is triggered, and we call it "continuousAlert" (you can name it whatever you want).

The function calls javascripts interval with "setInterval", and passes two variables - the first is what you'd like to run, and the second is time (in milliseconds) between each time it calls it.

In this case, we have it call an alert (with "TESTING" as it's alert text), and we tell it to wait 4 seconds (4000 milliseconds) between alerts.

Before the functions, you'll see we've created a variable called "myInterval" - this is used to hold the "interval", which allows us to later "clear" (or stop) it. Without this variable, we would have no way to tell Javascript to stop the continuous alert boxes from popping up.


Other things to think about

With intervals, you can do many things: