Introduction To CSS & AJAX
Introduction To CSS & AJAX
http://www.tuhocweb.com
Introduction to CSS
by Ross Shannon HTML was originally designed as a simple way of presenting information, with the aesthetics of a web page being far less important than the content (and largely being left up to the web browser). Of course, now that the web has become as popular as it has, the presentation of your content has become almost critical to a sites success. CSS is the key presentational technology that is used to design websites.
Page Navigation: What are Stylesheets? Benefits of CSS | Implementation One Central Stylesheet Attaching Your Stylesheet Individual Style blocks Using the Style Attribute
Benefits of CSS
Another of CSSs boons is that you define things once, making it far more efficient than defining everything in HTML on every page. This means: Pages download faster, sometimes by as much as 50% You have to type less code, and your pages are shorter and neater. The look of your site is kept consistent throughout all the pages that work off the same stylesheet. Updating your design and general site maintenance are made much easier, and errors caused by editing multiple HTML pages occur far less often.
http://www.tuhocweb.com
Well-authored CSS also improves the accessibility of web content, allowing access through myriad devices (handheld PDAs for example) and ensuring that web users with disabilities are still able to receive it. It also eliminates the need for browser-specific hacks and tags, which means your site has a better chance of working across all major browsers. Initially vaguely intimidating, CSS is a well-designed, elegant language. It is hugely important for the future of web design, and has been pivotal in helping designers move away from the problematic, hack-ridden days of presentational HTML tags like <font>, and allowed us to return to using logical, structural elements which make our sites more accessible. All that, and there are dozens of powerful extra formatting options and possibilities available through stylesheet commands that are not possible through normal HTML. Youll see these later on when we get on to things like backgrounds, spacing, layers and borders.
Implementation
CSS files are termed cascading stylesheets because of two reasons: one stylesheet can cascade, or have influence over, multiple pages. Similarly, many CSS files can define a single page. There are 3 ways to implement css commands into your site: Use one CSS file for all your pages. This is the best way to do it. Integrate CSS commands into the head of each of your documents. Use the style attribute to put CSS code directly into a HTML element. CSS allows you to use all three of these methods in glorious tandem, inheriting and overriding values as you go (well get on to all that in the next tutorial).
http://www.tuhocweb.com
This could be a new tag to you rel stands for the files RELationship, and type shows that its a text file acting as a CSS stylesheet. Once youve made sure that the href is correct (it can be defined absolutely or relatively), you should see your pages being formatted with your preferred values. You can link multiple stylesheets to each page if you want, like having one file with all your fonts, another for margins and spacing etc.
http://www.tuhocweb.com
If you use a common design across all of your sites pages, you should be using the method above. If, however, a number of pages need some particular styling and you need to override the values youve defined in your main stylesheet, you can use the style blocks method. To embed style, put this into your head:
<style type="text/css"> p {font-weight: normal; color: gray; } h1 {color: black; } </style>
The type attribute here allows browsers to treat this code as CSS. CSS code applied in this way is not technically a stylesheet , but is called an inline style block.
The style formatting will stop as soon as you close the tag its applied to, just like any other attribute, so it will be just this paragraph that will be affected. Also note that there arent any curly braces used here, but the colon/semicolon rule still applies. This method is useful for once-off formatting, and overriding previously defined properties, but you shouldnt use it very much. If you find yourself adding the same style to multiple tags, it might be worth your while promoting it to your main stylesheet, to save time and space. If youd like to see a fully-functioning stylesheet, you can look at ours: bubbleicious.css (use Notepad to open). Dont be overwhelmed by the complexity, as there are some more advanced techniques being used that havent been explained yet... So, that was your introduction. Now, gain some crucial control over your CSS with some slightly more advanced techniques...
Advanced CSS
by Ross Shannon First off, you're going to need a thorough grasp of the basics of CSS before you go into this. It's been easy so far, and this trend will continue here. CSS is a simple language with a lot of depth. There are many techniques you can use to get more out of your stylesheets. There's another implementation you've yet to learn; with classes and ids you will be able to set up custom ways of styling elements without having to change the fundamental properties of a HTML tag; and contextual style gives you yet another level of control.
http://www.tuhocweb.com
Page Navigation: Importing Stylesheets Implementation Overriding | classes and ids classes ids | <span> Overriding | Contextual Style
Importing Stylesheets
There is a fourth method of applying a stylesheet to your pages, suitable for CSS that you don't want old browsers trying to use. It is similar to the <link> method discussed in the introduction, but is only supported by browsers of versions 5 and above. Netscape and Internet Explorer 4 will not be able to read the stylesheet you supply this way, and so it is useful to apply things like positioning and CSS layout through this method, as old browsers mangle this code and occasionally crash if you give it to them. The code to import, which is placed in the <head>, is:
<style type="text/css" media="all"> @import "style.css"; @import "advanced.css"; </style>
It should be noted that this method is not available specifically to block out stylesheets to old browsers. It just happens that the two version 4 browsers did not support this implementation. This method is meant as a way to add partial stylesheets to your main sheets, so many sources are combined as one.
Implementation Overriding
CSS code can override other existing CSS code depending on how it is implemented. Say you had redefined the p tag in an external stylesheet. If you redefine it again in the head section of a document, this definition will be the one that is used, as it is closer to the things that it affects. Adding css using the style attribute will override anything else that has been specified elsewhere. Overriding-wise, the sheet imported last will override the imported ones that come before i.e. in the example above, 'advanced.css' has more weight than 'style.css' because it is imported below it. Imported stylesheets have the least influence over the final presentation of a page overall, as linked sheets will override them. So we finally have a full cascade order: the style attribute overrides a style block, which overrides a linked stylesheet, which overrides an imported sheet.
http://www.tuhocweb.com
Class selectors are created by typing a dot followed by the class name. Before you start putting in these, you should have an existing stylesheet or style block to add them to. That was all covered in the intro to CSS. Now, say you wanted to format lots of individual pieces of text as 12 point red Verdana. Adding the font face, color and size HTML around every instance where you want this type of text is a load of code, and a whole load of coding. This is the beauty of classes. Put this line of CSS into your style:
ids
ids are practically the same as classes, with one difference. Only one element can be given each id per page. They can
be used for elements you know will only occur once, such as header and navigation tables. If you want to use them, the code is the same, but with hashes (#) in place of the dots.
necessary for DHTML. Both class and id names can contain characters a-z, A-Z, digits 0-9, underscores and hyphens, but they cannot start with a number or dash.
<span>
Now, I'll introduce the span tag. It does exactly what you'd expect it influences any other code that it spans. So, to use it in conjunction with the class you set up above, do this:
<span class="caution">affected text</span>
This would create your desired text, without a font tag in sight. Note that the span tag does absolutely nothing on its own without the class attribute. The best part about class implementation is that it isn't confined to any one tag. You use span when there isn't any other tag around the text you want to affect. But; if the text is also being bolded, you can just add the class attribute to that instead, which means the text takes on the effects of the tag and the css in the class.
<b class="caution">text</b> will create text
http://www.tuhocweb.com
If you wanted all your instances of the class to be bold, you modify the class code and every occurrence of it on your site changes instantly. But if you only want one instance to be bold, you just add the class to the bold tag that's around that specific text. This saves you having to set up a whole new class when it would be inefficient to do so.
Overriding
If you wanted one of the instances of caution to be the same as the rest, but green instead of red, instead of setting up a whole new class with just this changed, you can override this aspect of the css by putting further style definitions closer to the affected text than the class that defines it. We'll call this 'overriding by proximity', because that sounds cool. For example:
<span class="caution" style="color: green">text</span>
Here I've embedded style into the tag, the most powerful overriding technique. If the caution class was specified in an external stylesheet I could have added the modification into a style block and it still would have overridden the class, due to the cascading order defined earlier on in this tutorial. In any case, the text will be displayed in 12pt green Verdana. If you want text vastly different, set up further classes. You can have an unlimited number, so long as they all have different names.
Contextual Style
Contextual style is a powerful technique that can save you from having to define too many classes. You can have your stylesheet apply CSS rules to an element, depending on what other elements it is contained in. For instance, if I wanted all strong elements that are contained in paragraphs to be red, I could write
sourcetip: All of you out there using XHTML should use lowercase selectors in your code, to match the all lowercase elements in your source code.
A rule like STRONG {color: red; } might not be applied, while strong {color:red; } is safe. For a further example, you could get all the links that occur in your navigation bar (which you've defined as div id="navigation") to be white with
CSS Layout
by Ross Shannon
http://www.tuhocweb.com
One of the major benefits of using CSS is that youre no longer forced to lay your sites out in tables. The layout possibilities of CSS give you complete control over the positions and dimensions of all page elements. If youve tried laying out a page with tables, you have probably been irritated in the past by the inability of your browser to render your page exactly as you had wanted. Table structures arent the most flexible of page layout devices, as they werent really designed for this purpose. Now however, with some reliable browser support in the current generation of browsers, you have a new and much improved option.
Page Navigation: Working with divs Floating Elements | CSS Positioning Absolute Positioning Positioning Layers Relative Positioning | Horizontal Centering
This example code uses some very simple CSS code. All block-level elements can have a width property, specified in units or as a percentage, and then I just added a background colour and some padding space around the div content.
Floating Elements
Since divisions are block-level (i.e., they default to 100% of the available screen width and add line breaks between each other), they will all just stack up underneath one another unless you position them in some way. The simplest way to do this is to use the CSS float property, the backbone of most CSS layouts. You can float any element left or right, and it will align itself over to the side of whatever element it is contained within.
#column1 {float: left; width: 200px; padding: 10px; } #column2 {float: left; width: 200px; padding: 20px; }
To create columned layouts, you simply float all of the column divisions to the same side and they will line up beside each other, as long as they fit. Laying out content in this way has immediate benefits such as progressive downloading (as the text is loaded it is displayed onto the page immediately, so your visitor can read as the page is forming around the text). You can also give each column specific margins and padding, giving you greater freedom to
http://www.tuhocweb.com
space your content out. Below is an example of code like the CSS above, with both div elements given the float: left; property: Column 1 Column 2 With these floating elements you can mimic a table structure, and have your page in a traditional layout without all the drawbacks of tables. Floating elements takes a little bit of practice (especially if the columns are not the same height), but can result in many traditional and non-traditional layouts. But CSS wasnt content to merely emulate the layout mechanisms of the past now you can control the position of elements on the page down to the pixel.
CSS Positioning
There are two other types of positioning beyond floating: absolute and relative. The codes youll be using are
tag {position: choice; top: 0px; bottom: 0px; left: 0px; right: 0px; } Browser Compatibility Note:
Absolute and relative positioning is a feature of the CSS2 specification and so is supported by Internet Explorer 4+, Mozilla, Firefox, Opera and Safari. For best results use the newest browsers available, as they will have improved and more accurate rendering capabilities. Do not use these if your users may be using older browsers.
Absolute Positioning
If you position an element (an image, a table, or whatever) absolutely on your page, it will appear at the exact pixel you specify. Say I wanted a graphic to appear 46 pixels from the top of the page and 80 pixels in from the right, I could do it. The CSS code youll need to add into the image is
Positioning Layers
To create what we call layers with the div tag, use code like this:
<div style="position: absolute; left: 610px; top: 80px; height: 400px; width: 100px; padding: 1em;">layer stuff</div>
First you specify the position of the layer, then its dimensions (which is optional, the layer will resize itself). If you want to give colour to the layers background, add the background-color: red; attribute in with the rest of your CSS code. As usual, you can use websafe colours, or named colours.
http://www.tuhocweb.com
Anything that could go on a normal page can be positioned with divs. They load far faster than, say, a table layout. Tables do not display on-screen until they have been downloaded in their entirety. With layers, all the information a browser needs is contained in the style attributes youve added. Therefore, it will display as soon as any part of it is downloaded. To get layers overlapping each other you need to use the z-index command. Add z-index: 1 in with the positioning code and this element will appear above everything without this command. If you want something else to go over this layer too, add z-index: 2 and so on. The higher the index, the closer the div will appear to the front of the page. Put the layer that holds your pages content at the top of your code. This is what readers want to see immediately. Your navigation and other presentational components can then load around this, allowing your reader to begin reading as soon as possible and making your navigation available when it is most likely to be used: after the page has been read. To see some examples of designs laid out with both float and absolute positioning, have a look-see at my redesigns section.
Relative Positioning
When you position something relatively, you are modifying its position from where it would have been if you hadnt changed anything. I find that to be the easiest way of thinking about it. For instance, in the next sentence, Ill offset some words 12px down and 22px right relative to their start position. Well, here are some words (some words) The words in parentheses are the words in their original positions, and the bold ones are the moved words. The CSS code to move them was
You should notice that if you want to move something left, you use the right code, and push it away from that side and vice-versa. To override an inherited position property, and make the element just a normal part of the page again, set it to position: static.
Horizontal Centering
Centering a div or any other block-level element horizontally is a special case for CSS layout, even moreso because there is a bug in Internet Explorers implementation of the standard way of doing it. The standard way is to set the elements horizontal margin values to auto, like so:
10
http://www.tuhocweb.com
center; }
Easy when you know how, eh? Be careful if youre planning on mixing absolute positioning and this centering method in the same layout. If you want other elements to be absolutely positioned inside the wrapper, make it relatively positioned first.
Ajax
by Ross Shannon When you want a user to send data to your server once they have filled out a form, for example they normally have to submit the form and then wait as the entire page is refreshed. Similarly, if you want to retrieve new data from the server, you have no choice but to load a whole new page. This is inefficient, time-consuming, and particularly frustrating if theres only a small amount of data being sent back and forth. In this tutorial, youll be introduced to Ajax, a technology that allows you to send these requests through small JavaScript calls, meaning the user doesnt have to wait for the page to refresh.
Page Navigation: What is Ajax? Cross-browser Ajax | Building a Request | Building the Script The Callback Function Sending the POST Request The Server-side Script Adding Feedback
What is Ajax?
Ajax is actually a family of technologies that have been available for years. The means to make requests to the server using only JavaScript were built into Internet Explorer 5.5, but the possibilities of the technology were overlooked. It was only in 2005 that the techniques were rediscovered and used, notably to excellent effect in Googles GMail web application. The term Ajax, which stands for Asynchronous JavaScript and XML, was first coined by Jesse James Garrett in his somewhat infamous article, Ajax: A New Approach to Web Applications. So lets take each of those parts in isolation. Ajax is: Asynchronous
11
http://www.tuhocweb.com
This means that when you send a request, you wait for the response to come back, but are free to do other things while you wait. The response probably wont come back immediately, so you set up a function that will wait for the response to be sent back by the server, and react to it once that happens. JavaScript JavaScript is used to make a request to the server. Once the response is returned by the server, you will generally use some more JavaScript to modify the current pages document object model in some way to show the user that the submission went through successfully. XML The data that you receive back from the server will often be packaged up as a snippet of XML, so that it can be easily processed with JavaScript. This data can be anything you want, and as long as you want. Theres nothing really new about what is happening here. Were requesting a file (which will often be a server-side script, coded in something like PHP), and receiving a page as the response. This is how the web works already the only difference is that now we can make these requests from JavaScript.
Cross-browser Ajax
Unfortunately Ajax is supported slightly differently in IE than it is Safari, Opera and Mozilla-based browsers like Firefox. This leaves us with two possible routes: using code branching to send the right code to each browser based on which model they support, or using a JavaScript library that wraps up the Ajax code into a single object, and means you dont have to worry about browser incompatibilities. Were going for the latter option, and will be using a JavaScript library. There are dozens of them in existence, each with their own boons and vices. Popular examples include prototype, Dojo, and the Yahoo UI library. For the duration of this tutorial, were going to be using a very useful library called Sarissa. Sarissa contains methods that will create the request for us, and also methods that help with processing the XML that we receive back in the response. This means we dont have to mess with the intricacies of Ajax, and allows our code to be quite elegant.
Building a Request
So, first download the Sarissa JavaScript source code file (called sarissa.js) and then upload it with the rest of your files. Youll need to show your pages where the library is, so add this line to the top of any pages that need access to Ajax:
<script type="text/javascript" src="sarissa.js"></script>
First of all, the project were going to work on throughout this tutorial is to make form submissions for a survey less painful. You can get a glimpse of what were aiming for in this example page. The user will be presented with a set of options, be asked to choose one, and press submit. Instead of having to reload the whole page to submit the form, which might turn some users off participating in the survey, we will instead submit the form with Ajax, and update the page when the request succeeds. Ill go through the four steps required to get this working, and well get onto the full code later. First well begin to construct our request. The specific method we use to do this is called XML HTTP Request. Through Sarissa, we create a cross-browser XML HTTP Request object:
var xmlhttp = new XMLHttpRequest();
That code there will take care of the browser compatibility issues, and leave you with an object that will work in whatever the users browser can support. Next we specify the page that were requesting:
xmlhttp.open('POST', 'rating-submit.php', true);
12
http://www.tuhocweb.com
The first argument to this function can be set to either 'GET' or 'POST'. In this instance, because were sending some data to the server, we use the POST method. If we were only pulling additional data from the server, we could use the GET method safely. This distinction is important to get right. Only use GET if you are not changing anything on the server, just retrieving some data. Otherwise you should always use POST. Keep the names capitalised. Obviously you will need to change that URL to the filename of the script youre using on your own server. The third argument controls whether the request is asynchronous or synchronous. If set to false, the call is made synchronous and the users browser will actually lock up until the response is received, which is not what we want. You will almost always leave this as true. The next step is to set up the function that will wait to be called until a response is returned by the server. This function is responsible for doing something to show the user that the submission has succeeded. Usually, adding a small message to the page is enough. The callback function, as it is called, always follows the same structure, which looks like this:
xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4) { // Your callback code goes here } }
As a request is made, it passes through various states. We check the objects readyState property here to see if it has made it to stage 4, which means that the response is complete. The last step now that this is all set up is to actually send the request:
xmlhttp.send(null);
This will send the request and then return immediately. It then waits for the response to enter readyState 4. When that happens, your callback function is called, and whatever data was sent back in the response (if any) is available in the xmlhttp.responseXML variable. And thats all there is to it.
So here were first checking if the users browser has correctly loaded the Sarissa object, and is also able to do the document.getElementsByTagName method. If this doesnt work out, we return early. Then were looping through all
13
http://www.tuhocweb.com
the forms on the page and adding an event handler to any that have a class name that matches the string ajaxify. Next we have to actually write that submitRating function. It looks like this:
function submitRating(e) { knackerEvent(e); var target = window.event ? window.event.srcElement : e ? e.target : null; if (!target) return;
/* Cancel the submit event, and find out which form was submitted */
Just because weve received a response back doesnt mean that everything went according to plan. When the response is sent back by the server, it is always sent with a status code, of which there are many. The response code 200 (known as Ok) means that the response went through without a hitch, which is obviously what we want to hear. If xmlhttp.status is set to 200, then we can go ahead and add some feedback to the page. Otherwise, in the case of a timeout or if the script returned a 404 error, we need to have a backup plan. Here, Ive decided to simply submit the form normally. This illustrates an important point: even with all of this Ajax goodness, you still need to have a script on the server that will deal with normal form submits from users with browsers that dont support Ajax, or just for those times when something goes wrong.
14
http://www.tuhocweb.com
As you can see, were no longer simply calling send(null). We send the data from the form in the format name=value&name=value.... So here were working with the select called rating, and sending its value, which will end up looking something like rating=3.
Adding Feedback
The final step is to check the response and add feedback to the page appropriately. Again, this will be different for everyones implementation. The XML that was sent back by your server-side script is available in the xmlhttp.responseXML property. You can treat this just as you would a HTML document, which means that methods calls like the one below will yield the contents of certain elements in the XML:
xmlhttp.responseXML.getElementsByTagName('result')[0].firstChild.data;
That code snippet above will return the contents of the first <result> element in the response (i.e. the value you should check to make sure the server-side script executed correctly). The feedback you give the user can range from popping up an alert() to rearranging the page using DOM calls. In the example page you can see that I add new text to the page, restyle the form and then disable the form inputs so that the user doesnt submit the same form twice. So there you have it, an Ajax-ified page from start to finish. Ajax has lots of useful applications. Have fun with it.
15