CSS ─ Syntax

A CSS comprises of style rules that are interpreted by the browser and then applied to the corresponding elements in your document. A style rule is made of three parts:

Selector: A selector is an HTML tag at which a style will be applied. This could be any tag like or etc.

Property: A property is a type of attribute of HTML tag. Put simply, all the HTML attributes are converted into CSS properties. They could be color, border, etc.

Value: Values are assigned to properties. For example, color property can have the value either red or #F1F1F1 etc.

Syntax– selector { property: value }

Example: You can define a table border as follows:
table{ border :2px solid #C00; }

Here table is a selector and border is a property and the given value 2px solid #C00 is the value of that property.

Read More

Advantages of CSS

  • CSS saves time – You can write CSS once and then reuse the same sheet in multiple HTML pages. You can define a style for each HTML element and apply it to as many web pages as you want.
  • Pages load faster – If you are using CSS, you do not need to write HTML tag attributes every time. Just write one CSS rule of a tag and apply it to all the occurrences of that tag. So, less code means faster download times.
  • Easy maintenance – To make a global change, simply change the style, and all the elements in all the web pages will be updated automatically.
  • Superior styles to HTML – CSS has a much wider array of attributes than HTML, so you can give a far better look to your HTML page in comparison to HTML attributes.
  • Multiple Device Compatibility – Style sheets allow content to be optimized for more than one type of device. By using the same HTML document, different versions of a website can be presented for handheld devices such as PDAs and cellphones or for printing.
  • Global web standards – Now HTML attributes are being deprecated and it is being recommended to use CSS. So it’s a good idea to start using CSS in all the HTML pages to make them compatible with future browsers.
Read More

Introduction of Css

Cascading Style Sheets, fondly referred to as CSS, is a simple design language intended to simplify the process of making web pages presentable.
CSS handles the look and feel part of a web page. Using CSS, you can control the color of the text, the style of fonts, the spacing between paragraphs, how columns are sized and laid out, what background images or colors are used, as well as a variety of other effects.
CSS is easy to learn and understand but it provides a powerful control over the presentation of an HTML document. Most commonly, CSS is combined with the markup languages HTML or XHTML.

Read More

Positioning Browser Windows

o      The screen object provides you with access to properties of the user’s computer display screen within your JavaScript applications.

o   Some of the available properties are:

Property

Description

availHeight

The pixel height of the user’s screen minus the toolbar and any other permanent objects (eg the Windows Taskbar)

availWidth

As availHeight, but dealing with horizontal space

colorDepth

The maximum number of colours the user’s screen can display (in bit format, eg 24 bit, 16 bit etc)

heightThe true pixel height of the user’s display

width

The true pixel width of the user’s display

o      The left and top parameters of the open() method enable you to specify the position of a window on screen by specifying the number of pixels from the left and top of the screen respectively.

o     If you need to use a variable to specify the value of a parameter in the open() method, you would do so as follows:

window.open(“index.html”, “window_name”,“width=200,height=200,left=”+var_left+“top=”+var_top);

                       Where var_left and var_top are the appropriate variables.

o       Note the use of the + operator to ensure that the third parameter in the open() method remains as one string when variables are added.

o       In order to centre the window on the user’s screen, a little simple geometry is required. The centre of the screen is obviously the point found when we take the width of the screen divided by two, and take the height of the screen divided by two. However, if we set the window’s top and left values to these coordinates, the top left corner of the window will be centred, not the window itself.

o      In order to centre the window, we need to subtract half of the window’s height from our top value, and half of the window’s width from our left value. A simple script to accomplish this is as follows:

         win_width = 200; win_height = 200;

    win_left = (screen.availWidth/2)– (win_width/2);

    win_top = (screen.availHeight/2)– (win_height/2);

o       By using this script, the values of win_left and win_top will be set correctly for any window using win_width and win_height appropriately to be centred on the screen.

Project

o      Open your previous project file, and save it under the name chapter_26.html.

o     Modify your existing code to ensure that the logo appears centred on the user’s screen. If possible, do not modify your original function by doing anything more than two new functions – get_win_left( width ) and get_win_top( height ).

Read More

Working with Browser Windows

o      Using standard HTML links, we can open new browser windows:

           <a href=”#” target=”_new”>link</a>

o       The amount of control this method affords us over the resultant image, however, is nil. We cannot control the size, shape,   location on the screen or anything else about that window with this method.

o      JavaScript allows us much finer control, as we may expect:

         window.open( page_url, name, parameters );

o       As we can see from the above prototype, there are only three arguments that this method can take. However, the parameters argument is actually more complex than we might assume:

        ”param1,param2,param3,param4…”

                    since we can use it to add many parameters to the method. Note there are no spaces in the parameter list.

o       name is used to give the window an HTML name – so we can use that name to open links into the new window using the “target” method above.

o       The return value from the open method is an object variable referring to the newly opened window. In other words, if we open a new window like so:

        win = window.open(“page.html”, “”, “”);

we can use the object variable win to alter the new window through JavaScript.

o       A practical example – let’s say we want to open a new window 300 pixels high by 400 pixels wide, and display the BBC news page in it. The following code would suffice:

  window.open(“http://news.bbc.co.uk/”,“bbc”, “width=300,height=300”);

o      Some available parameters are given in the table below:

ParameterValueFunction
locationYes/NoSpecifies whether or not the location (address) bar is displayed
menubarYes/NoSpecifies whether the menu bar is displayed
status Yes/NoSpecifies whether the status bar is displayed
widthPixels Specifies the width of the new window
heightPixelsSpecifies the height of the new window
resizableYes/NoAllow or disallow window resizing
scrollbarsYes/NoAllow or disallow window scrolling

o      If no parameters are set, then the value of each parameter is set to “yes” where appropriate. For example:

       window.open(“http://www.bbc.co.uk/”,“bbc”, “”);

is equivalent to:

      <a href=”http://www.bbc.co.uk/” target=”bbc”>

o      However, if any parameter is set, all others default to “no”. So if you wanted to have a scrollbar but nothing else, the following would suffice:

   window.open(“http://www.bbc.co.uk/”,“bbc”, “scrollbars=yes”);

Project

              o     Open your previous project file, and save it under the name chapter_25.html.

                  o     Remove all functions and HTML from your previous file, leaving only the logo image and the link.

                  o      Create a function in the head area script element called view_new_logo. This function should:

§  Open a new window 200 pixels square.

§  Load the image rocollogo.jpg from the images folder.

§  Be called RocolLogo

§  Be stored in an object variable called objNewLogo.

§  Have no scrollbars, be of a fixed size, and have no other features where possible.

o Remove all event handlers from the link, and add a new one to run the function above when the link is clicked.

o   Once you have verified that a window pops up as required when the link is clicked, test each parameter from the table above in the function.

Read More

Object Instantiation and Better Rollovers

o      So far we have seen a very simple example of an image rollover. It is functional and works as desired, but it is lacking in a few finer details.

o      Specifically, when we use JavaScript to change the src attribute of an <img> tag, the browser has to load this image from scratch. On our local machine, this will not cause an appreciable delay, but when dealing with a remote server (as we will be on the Internet), this delay can lead to a noticeable “lag”, which can destroy the feeling of a dynamic interface.

o      Ideally, we would like to instruct the browser to load any alternate images when it loads the page. This will allow us to ensure that the new images are sitting on the user’s computer, ready to be swapped in and out instantly.

o      To do this, we need to look at object variables and object instantiation (or creation). In particular, we need to look at the Image object.

o       Each <img> tag on the page has a corresponding Image object in JavaScript. We have looked at ways of manipulating this directly, and have an idea of some of the properties an Image object can have.

o       However, we can create Image objects directly in JavaScript, without the need for a corresponding <img> tag on the page. When we create such an object, and set its src property, the browser will load the appropriate file into memory, but will not display the image on the page. 

o       In other words, we can create “virtual” images that exist within JavaScript, and use these Image objects to store the alternate images for our “real” images.

o     To create an Image object (in fact, to create any object), we need to use the following code:

             virtual_image = new Image();

o       We have seen this sort of syntax before – the use of the new keyword when we created our Arrays. new tells JavaScript that we are creating a new object. The virtual_image part of the assignment is just a variable name. In this case, the variable is an Object Variable, since it contains an object.

o        To use this variable to preload our images, we take advantage of the fact that it has the same properties and methods as any other image:

          virtual_image.src = “contactsover.jpg”;

o      The browser will now preload our image, ready to be swapped in at a later time.

Project

o       Open your previous project file, and save it under the name chapter_24.html.

o      Starting with your previous code, create a new function called preload_images in the head area script element of your page.

o       Use this function to create seven new image objects, and use each objects corresponding object variable to preload your “over” image variations.

o      Check your work in your browser to ensure that the image swapping still works as expected.

o       Add your preload_images function to the body tag of your page to ensure that it runs when the page has finished loading. Use the following syntax:

       <body onload=”preload_images();”>

o       Once you have verified that the image swapping still works as expected, expand your preload_images function to define an array of images to preload, and then use a for loop to move through the array and assign each image to the src property of an object variable. Hint: an object variable can be anything that can store information – for example an array element.

                      Check your work in your browser.

Read More

Simple Image Rollovers

o      A simple image rollover is an effect which happens when the mouse appears over an image (usually a linked button) on the page. The original image is replaced by another of equal size, usually giving the effect that the button is highlighted in some way.

o      With what we have learned so far, we already have the ability to create a simple image rollover effect. All that remains is to clarify the particulars of the process:

o      The page is loaded and the original image appears on the page as specified by the <img> tag’s src attribute.

o     The mouse moves offer the image and the alternative image is loaded into place.

o     The mouse leaves the image and the original image is loaded back.

o      As you may have realised, we are going to use JavaScript to alter the src attribute of the image tag. The best way to think of this is to picture the <img> tag as simply a space on the page into which an image file can be loaded. The src attribute tells the browser which image to load into the space, and so if we change that value, the image will be changed.

o      In other words, the id attribute of the <img> tag is naming the “space”, not the image.

o       Now, in order to alter the src attribute with JavaScript, we need to tell JavaScript which image “space” we want to alter. We use the id attribute along with the getElementById() method from the last chapter to do this:

 button_img =document.getElementById(“button”);

           button_img.src = “new_image.jpg”;

      o   We can directly insert this code into the image’s event handler:

 <img src=”old.jpg” id=”button” onmouseover=”document.getElementById(‘button’).src’new.jpg’;”>

  Note that this code is suddenly very convoluted. There are two immediate potential solutions. The first is to define a function:

            function swap_image( id, new_image )

          {

           img = document.getElementById(id); 

           img.src = new_image;

          }

            

           <img src=”old.jpg” id=”button” onmouseover=”swap_image(‘button’, ‘new.jpg’);”>

o       This is a much cleaner solution, and more importantly we can use this for any images on the page, simply by changing the arguments of our function call. We can also use the function to achieve the “swap back” functionality: 

            … 

      <img src=”old.jpg” id=”button” onmouseover= ”swap_image(‘button’, ‘new.jpg’);”onmouseout=”swap_image(‘button’, ‘old.jpg’);”>

o       We can go even further in “cleaning up” our code, though. Because the event handler is being used to alter the object which is experiencing the event (ie, the mouse is moving over the image tag that we are trying to change), we can use the “automagic” JavaScript object this to perform the operation: 

     function swap_image( img, new_image )

  {

    img.src = new_image;

  }

   … 

   <img src=”old.jpg” id=”button” onmouseover=”swap_image(this, ‘new.jpg’);”>

o       Note a couple of things. Firstly, this has no quotes around it – we are using it like a variable name. Secondly, our function now uses the first argument directly, instead of using it to get the relevant object from the page. We can do that because this is actually an object – it’s an object that takes on the properties and methods of whatever object it is called from, in this case, it becomes equivalent to

      document.getElementById(‘button’), although is obviously much shorter!

o      Using this has some limitations. For example, if we wanted to change the src attribute of any other image on the page when the mouse moved over “button”, we would be unable to use this, and hence would have to define another function that could take an id as its argument and get the relevant object that way.

Project

o      Copy the folder called buttons from the network drive to your project folder. o Open your previous project file, and save it under the name chapter_23.html. o Clear all JavaScript code from your script tags.

o     Ensure that you have a script element in the head area of your document, and none in the body area.

o      Within the body area of your page, create a paragraph containing six image elements. Set the src attributes of the images to load the following files in your copied buttons folder, and give each a sensible id:

o     contacts.jpg o   home.jpg o   people.jpg o   products.jpg o  quotes.jpg o  whatsnew.jpg

o      Create a JavaScript function in the head area script element that takes two arguments – an id and a file name. It should alter the src property of the appropriate image object to the file name given.

o     Use this function to swap the src attribute of the contacts button to contactsover.jpg when the mouse moves over the image.

o   Once you have this working, update the remaining five images with event handlers to swap their src attributes to their appropriate “over” image.

o      Add event handlers to all six images to ensure that they return to their original state when the mouse is moved away from them. Check your work in your browser

o     Add a new paragraph above the previous one, and add an <img> tag to it to containing the file rocollogo.jpg from the images folder.

o      Add a text link to a new paragraph between the two paragraphs. The link should be a “dummy” link (ie use “#” as its href attribute value), but when the mouse moves over it, the image above it should change to show rocollogo.gif.

o      Moving the mouse away from the text link should return the logo to its previous state.

o     Check your work in your browser.

Read More

Using Event Handlers

o      So far, our scripts have run as soon as the browser page has loaded. Even when we have used functions to “package” our code, those functions have run as soon as they have been called in the page, or not at all if no call was made. In other words, the only event our scripts have so far responded to has been the event of our page loading into the browser window.

o       Most of the time, however, you will want your code to respond specifically to user activities. You will want to define functions, and have them spring into action only when the user does something. Enter event handlers.

o       Every time a user interacts with the page, the browser tells JavaScript about an “event” happening. That event could be a mouse click, a mouse pointer moving over or out of a given element (such as an image or a paragraph), a user tabbing to a new part of an HTML form, the user leaving the page, the user submitting a form and so on.

o       An event handler is a bit of JavaScript code that allows us to capture each event as it happens, and respond to it by running some JavaScript code.

o       In general, we attach event handlers to specific HTML tags, so a mouse click on one element of the page might be captured by an event handler, but clicking somewhere else might do something completely different, or indeed nothing at all. o Some common event handlers are in the table below:

Event Handler

Occurs When…

onloadAn element is loaded on the page

onunload

An element is not loaded, for example when a user leaves a page

onmouseoverWhen the mouse pointer enters the area defined by an HTML element

onmouseout

When the mouse pointer leaves the area defined by an HTML element

onclickWhen the left mouse button is clicked within the area defined by an HTML element

onmousedown

When the left mouse button is depressed within the area defined by an HTML element

onmouseupWhen the left mouse button is released within the area defined by an HTML element

o      The last three are related, but there are subtle differences – onclick is defined as being when both mousedown and mouseup events happen in the given element’s area. For example, if you click on an area of the page, that registers the area’s mousedown event. If you then hold the mouse down and move to another area before releasing, it will register the other area’s mouseup event. The browser’s click event, however, will remain unregistered.

o     In theory, we can add most of these event handlers to just about any HTML tag we want. In practise, many browsers restrict what we can interact with.

o      We will mostly be attaching event handlers to <img><a> and <body> tags.

o      To attach an event handler to a tag, we use the following method:

            <a href=”…” onclick=”a_function();”>link</a>

o       We can use this method to attach any event handler listed above to the elements of the page. In addition to calling functions (with any optional arguments, of course), we can write JavaScript directly into our event handlers:

          <a href=”…” onclick=”alert(‘hello’);”>link</a>

o      Note the potential issue with quote marks here – if you use double quotes around your event handler, you need to use single quotes within and vice versa.

Project

o       Open your previous project file, and save it under the name chapter_21.html. o Clear all JavaScript code from your script tags.

o      Ensure that you have a script element in the head area of your document, and none in the body area.

o      Within the head area script element, define the following function:

       function set_status( msg )

     {

      window.status = msg; }

o        When called, this function will set the text displayed in the browser’s status bar (the part of the window below the page content) to whatever is passed as an argument. For example, to set the status bar to display “Welcome”, we would call:

             set_status(“Welcome”);

o   Now define the following function immediately below the last:

        function clear_status( )

      {

        set_status(“”); }

o       When called, this function will clear the status bar. Notice that we are using our previous function within the new one. This is a common programming technique that allows us to define functions of specific cases using more general functions.

o       Now, add the following HTML to the body area of your page. Remember, we’re adding HTML here, not JavaScript, so do not be tempted to use script tags for this part of the project:

            <a href=”#” 

     onmouseover=”set_status(‘hello’);” onmouseout=”clear_status();”>testing</a>

o      Load the page in your browser and observe what happens when you move your mouse over the link.

o     The # value for the href attribute of the link allows us to define a “dead” link on the page. Clicking on the link will take you nowhere – try it.

o     Now, alter the code to have the link point at a real website that you know of.

o     Clicking on the link now will take you away from the page. Let’s say we want to suppress that behaviour.

o      When an event handler intercepts an event, it pauses the normal action of the event. For example, if you used an onclick handler on a link to pop up an alert box, the link would only be followed after the alert box had been dismissed. We can use event handlers to cancel the action if required by using their return values.

o     Add a new function to the head area script element:

        function confirm_link( )

   {   check = confirm(“This will take you away from our site. Are you sure?”);   return check; }

o      The value of check will be true or false.

o      Now, modify your link to contain the following event handler:

onclick=”return confirm_link();”

       By using the word return in our event handler, the response of the function will be used to decide whether the rest of the normal action is run. In this case, if confirm_link() returns false, our link action will be cancelled. o Load your page in your browser and view the result.

Read More

Logical Operators

o       In our discussion of conditionals, we saw how to check the veracity of a single condition via a comparator:

 if ( x > some_value )

{

  …expressions… }

o       We have also seen the limitations of such an approach. Let us say we wanted to discover if lay between two values, say val_1 and val_2. There are a number of ways we could achieve this. In our example on student grades, we learned that we could use an if…else pair to achieve this effect:

    if ( x > val_1 )

  {

    …do something…

  } else

    if ( x > val_2 )

 {

   …do something else… }

o       The above code achieves what we want – for the second branch, x must lie between val_2 and val_1 (assuming val_1 is greater than val_2, of course). However, it’s rather unwieldy, and does not scale elegantly to checking three conditions (say we wanted to check if x was an even number as well), or in fact to ten conditions.

o       Enter Logical Operators. These operators are used to join together conditional checks and return true or false depending on whether all or any of the checks are true.

o      In English, we refer to these operators by using the words “AND” and “OR”.

o       For example, say we wanted to do something each Tuesday at 8pm. We would want to check whether the current day was Tuesday, and whether the time was 8pm.

o       Another example: Let’s say we wanted to do something on the first Tuesday of each month, and also on the 3rd of the month as well. We would have to check whether the current day was the first Tuesday of the month, or whether it was the 3rd day of the month. 

Note in the last example, if both conditions were true, then we would be on Tuesday the 3rd and would perform the action. In other words, an or condition allows for either one, or the other, or bothconditions to be true.

o      In JavaScript, we use the following syntax to check multiple conditions:

       ( 100 > 10 && 5 < 8 )

translates as “if 100 is greater than 10 and 5 is less than 8”. In this case, the result is true.

       ( 100 > 200 && 4 < 9 )

in this case, the result is false. Note here that only the first condition is actually checked. Since and requires both comparisons to be true, as soon as it finds a false one it stops checking. This can be useful.

       ( 100 > 10 || 9 < 8 )

translates as “if 100 is greater than 10 or 9 is less than 8”. In this case, the result is true, since at least one of the conditions is met.

       ( 100 > 200 || 4 > 9 )

in this case, the result is false since neither of the comparisons are true. Finally:

       ( 100 > 200 || 5 < 2 || 3 > 2 )

in this case, the result is true. Any one of the three being true will provide this result.

o     As we can see from the last example, this method of checking scales to any number of conditions. We can also mix and match the operators. For example:

               ( ( 100 > 200 && 100 > 300 ) || 100 > 2 )

in this case, the and condition evaluates to false, but since either that or the last condition has to be true to return true, the overall condition returns true as 100 is indeed greater than 2.

o      This sort of complex logic can take a while to comprehend, and will not form a set part of the course. However, it is useful to be aware of it.

Project

o   Open your previous project file, and save it under the name chapter_20.html. o Clear all JavaScript code from your script tags.

o    Ensure that you have a script element in the head area of your document, and one in the body area.

o      Copy the file available_plugins.js from the network drive (your tutor will demonstrate this), and open it using NotePad’s File > Open command.

o       Copy and paste the entire contents of available_plugins.js into your current project file, into the script element in the head area of your page.

o      Have a read through the code. Note that it defines a large, two dimensional array. The array has a list of various components that can be present in web browsers (such as Flash or Quicktime)

o      Add a function to the head area script element, called flash_exists(). This function should use a for loop to check each of the elements of the available_plugins array and establish if Flash is present.

o     Add a further function to the head area script element, called quicktime_exists(). This function should also use a for loop to check each element of the array, this time returning true if Quicktime is present. o Finally, add a function to the head area script element called both_quicktime_and_flash_exist(). This function should call both of the previous functions, store their results in a variable, and produce an alert box containing the message: o “Both Quicktime and Flash” if both functions returned true; or:

o   “One of Quicktime or Flash is missing” if either of the functions return false.

       Call the final function from the body area script element.

o  Check your results in your browser.

Read More