Wednesday, October 31, 2007

Great CSS Resources

MORE INFORMATION


www.sitepoint.com/article/css-is-easy

SitePoint’s easy introduction to the world of CSS is a great place to start.


www.w3schools.com/css

W3Schools’ CSS tutorials are helpful whether you’re learning from scratch, or simply brushing up on your knowledge of CSS.


www.csszengarden.com

The CSS Zen Garden is a marvellous demonstration of the power of cascading style sheets alone. It has a real wow factor!


www.centricle.com/ref/css/filters

This comprehensive list of CSS hacks shows you which browsers will be affected by a given hack, if you need to hide certain CSS directives (or deliver certain directives) to a particular browser.


www.positioniseverything.net

This site demonstrates CSS issues in various browsers and explains how to work around them.


www.css-discuss.org

The CSS-Discuss mailing list is ‘devoted to talking about CSS and ways to use it in the real world; in other words, practical uses and applications.’ The associated wiki is a repository of useful tips.


www.sitepoint.com/books

If you’re after something more definitive, HTML Utopia: Designing Without Tables Using CSS is a complete guide for the CSS beginner. The CSS Anthology: 101 Tips, Tricks & Hacks is a perfect choice if you prefer to learn by doing. A lot of tutorials on the web cover JavaScript. Some explore both DHTML and the DOM, while others do not; you should try to find the former.


www.sitepoint.com/article/javascript-101-1

This tutorial provides an introduction to the basics of JavaScript for the total non-programmer. Some of the techniques in this article aren’t as modern as the alternatives we’ve presented here, nonetheless you’ll get a good feel for the JavaScript language itself.


www.quirksmode.org

Freelance web developer Peter-Paul Koch’s list of CSS and JavaScript techniques and scripts covers a considerable amount of useful ground in this area.

Building Dynamic Web Sites

Use our brief overview to find out about the building blocks that make up DHTML websites – from what HTML really is, to adding interactivity using JavaScript…


DHTML is actually a combination of proper HTML for your content, Cascading Style Sheets for your design and JavaScript for interactivity. Mixing these technologies together can result in a humble stew or a grandiose buffet. It’s all in the art of cooking, so let’s begin…


HTML starting points


Websites are written in HTML. For a successful DHTML-enhanced website, it’s critical that your HTML is two things: valid and semantic. These needs may necessitate a shift away from your previous experiences writing HTML. They may also require a different approach.


A specific set of rules, set out in the HTML recommendation, dictate how HTML should be written. HTML that complies with these rules is said to be “valid”. Your HTML needs to be valid so that it can be used as a foundation on which you can build DHTML enhancements. While the set of rules is pretty complex, you can ensure that your HTML is valid by following a few simple guidelines.


Correctly nest tags


Don’t let tags “cross over” one another. For example, don’t have HTML that looks like this:


Here is some <strong>bold and <em>italic</strong> text</em>.


Here, the <strong> and <em> tags cross over one another; they’re incorrectly nested. Nesting is extremely important for the proper use of DHTML. If you cross your tags, each browser will interpret your code in a different way, according to different rules (rather than according to the standard). Any hope of your being able to control the appearance and functionality of your pages across browsers goes right out the window unless you do this right.


Close container tags


Tags such as <strong> or <p>, which contain other items, should always be closed with </strong> or </ p>, or the appropriate closing tag. It’s important to know which tags contain things (e.g. text or other tags) and to make sure you close them. <p>, for example, doesn’t mean “put a paragraph break here”, but “a paragraph begins here”, and should be paired with </p>, “this paragraph ends here”. Those who know what they’re doing with container tags will be aware that HTML 4.01 doesn’t actually require that all container tags are closed, though XHTML still does. However, it’s never invalid to close a container tag, though it is sometimes invalid to not do so. It’s considerably easier to just close everything than it is to remember which tags you’re allowed to leave open. The same logic applies to <li> tags as well.


Always Use a Document Type


A document type (or DOCTYPE) describes the dialect of HTML that’s been used; there are several different options. Here, we’ll use the dialect called HTML 4.01 Strict. Your DOCTYPE should look like this:


<!DOCTYPE HTML PUBLIC “-//W3C [13]//DTD HTML 4.01//EN”

“http://www.w3.org/TR/html4/strict.dtd”>


That information can be typed on a single line, or with a line break after EN”. Be sure to place it at the top of every page. The article Fix your site with the right DOCTYPE! published on www.alistapart.com lists all the DOCTYPEs you might want to use.


The most important page creation step is to check that your HTML is valid. There are numerous tools that you can download and run to test your code’s validity – some HTML editors even have such tools built in – or you can use one of the many online validators, the most common of which is the W3C’s own validator (validator.w3.org). A validator will tell you how you need to adjust your HTML in order to make it compatible with DHTML techniques. The ultimate reference for what constitutes valid HTML is the HTML recommendation (www.w3.org/TR/html4). It’s complex and detailed, but you’ll find the answers there. As mentioned above, browsers rely on a standard that describes how validated HTML should be interpreted. However, there are no standards to describe how invalid HTML should be interpreted; each browser maker has established their own rules to fill that gap. Sticking to valid HTML means that any problems you find are deemed to be bugs in that browser – bugs that you may be able to work around.


Step up to semantic HTML


In addition to its validity, your HTML should be semantic, not presentational. What this means is that you should use HTML tags to describe the nature of an element in your document, rather than the appearance of that element. So don’t use a <p> tag if you mean, “put a blank line here”. Use it to mean, “a paragraph begins here” (and place a </p> at the end of that paragraph). Don’t use <blockquote> to mean, “indent this next bit of text”. Use it to mean, “this block is a quotation”. If you mark up your HTML in this way, you’ll find it much easier to apply DHTML techniques to it further down the line. This approach is called semantic markup – a fancy way of saying, “uses tags to describe meaning”.


Let’s look at a few example snippets. First, imagine your website has a list of links to different sections. That list should be marked up on the basis of what it is: a list. Don’t make it a set of <a> tags separated by <br> tags; it’s a list, so it should be marked up as such, using <ul> and <li> tags. It might look something like this:


<ul>

<li><a href=”index.html”>Home</a></li>

<li><a href=”about.html”>About this Website</a></li>

<li><a href=”email.html”>Contact details</a></li>

</ul>


You’ll find yourself using the <ul> tag a lot. Many of the items within a website are lists: a breadcrumb trail is a list of links, a menu structure is a list of links and a photo gallery is a list of images. If your list contains items with which comments are associated, it should be marked up as a definition list:


<dl>

<dt><a href=”index.html”>Home</a></dt>

<dd>Back to the home page</dd>

<dt><a href=”about.html”>About this Website</a></dt>

<dd>Why this site exists, how it was set up, and who did it

</dd>

<dt><a href=”email.html”>Contact details</a></dt>

<dd>Getting in contact with the Webmaster: email addresses and phone numbers</dd>

</dl>


Remember: the way your page looks isn’t really relevant. The important part is that the information in the page is marked up in a way that describes what it is. There are lots of tags in HTML; don’t think of them as a way to lay out information on your page, but as a means to define what that information means. If you don’t use HTML to control the presentation of your pages, how can you make them look the way you want them to? That’s where Cascading Style Sheets come in.


Adding CSS


Cascading Style Sheets (CSS) is a technique that enables you to describe the presentation of your HTML. In essence, it allows you to state how you want each element on your page to look. An element is a piece of HTML that represents one thing: one paragraph, one heading, one image, one list. Elements usually correspond to a particular tag and its content. When CSS styles are used, DHTML pages can work on the appearance and the content of the page independently. Imagine you want your main page heading (an <h1> tag) to be displayed in big, red, centred text. You should specify that in your style sheet as follows:


h1 {

font-size: 300%;

color: #FF0000;

text-align: center;

}


See More information for some links to introductory tutorials on CSS, which should help if the above lines don’t make a lot of sense to you.


The key point here is to remove the presentation aspects from your HTML and put them into your style sheet. If, for example, you made your page heading bigger by putting <font> tags in your HTML, then you’d need to paste those tags into every page on which a header was used. By making your HTML semantic and moving the page’s presentation into CSS, you can control the look of headings across the whole site through a single style sheet.


Of course, it’s not quite as easy as that. Although the full definition of CSS enables you to do some fairly amazing things, and to control the presentation of your pages to a high degree, not every browser supports everything that CSS has to offer.


In order to know about the differences in browser support for CSS, you need to know what CSS can do. There are two sorts of browser incompatibilities: things that a given browser doesn’t implement and things that it implements incorrectly.


Missing implementations are relatively easy to deal with: don’t rely on such rules if you want your CSS to work in browsers that have failed to implement them. This can be a pain, especially since the most commonly used browser in the world, Internet Explorer for Windows, has some serious holes in its CSS support; however, this “solution” is often a necessary compromise.


Badly implemented standards are a bigger problem. In such cases, the browser gets it wrong. You’ll need to understand exactly what each browser does wrong, and how you can work around those failings. You’ll pick up this knowledge as you go along. Workarounds for CSS bugs in different browsers are usually achieved using CSS hacks. These hacks take advantage of the bugs in a browser’s CSS parser to deliver specific style sheet directives that work around its poor implementation of the standards. A huge variety of these CSS hacks is documented for each browser in various places around the web.


Learning to understand and adapt to the vagaries of CSS handling in various browsers is part of the work that’s required to use CSS effectively. While it can be a lot of work, many CSS bugs only become apparent with the complex use of this technology; most CSS is handled perfectly across platforms and browsers without the need for hacks or complex tests. While CSS is powerful, it doesn’t quite give us true flexibility in presentation. The capabilities of CSS increase all the time, and more “interactive” features are constantly being added to the CSS specification. However, it’s not designed for building truly interactive websites. For that, we need the final building block of DHTML: JavaScript.


Adding JavaScript


JavaScript is a simple but powerful programming language. It’s used to add dynamic behaviour to your website. HTML defines the page’s structure and CSS defines how it looks, but actions, the things that happen when you interact with the page are defined in JavaScript. JavaScript works with the Document Object Model to attach actions to different events (mouseovers, drags, and clicks). The ‘More information’ box below has some links to a few JavaScript tutorials if you need them.




MORE INFORMATION



www.sitepoint.com/article/css-is-easy

SitePoint’s easy introduction to the world of CSS is a great place to start.


www.w3schools.com/css

W3Schools’ CSS tutorials are helpful whether you’re learning from scratch, or simply brushing up on your knowledge of CSS.


www.csszengarden.com

The CSS Zen Garden is a marvellous demonstration of the power of cascading style sheets alone. It has a real wow factor!


www.centricle.com/ref/css/filters

This comprehensive list of CSS hacks shows you which browsers will be affected by a given hack, if you need to hide certain CSS directives (or deliver certain directives) to a particular browser.


www.positioniseverything.net

This site demonstrates CSS issues in various browsers and explains how to work around them.


www.css-discuss.org

The CSS-Discuss mailing list is ‘devoted to talking about CSS and ways to use it in the real world; in other words, practical uses and applications.’ The associated wiki is a repository of useful tips.


www.sitepoint.com/books

If you’re after something more definitive, HTML Utopia: Designing Without Tables Using CSS is a complete guide for the CSS beginner. The CSS Anthology: 101 Tips, Tricks & Hacks is a perfect choice if you prefer to learn by doing. A lot of tutorials on the web cover JavaScript. Some explore both DHTML and the DOM, while others do not; you should try to find the former.


www.sitepoint.com/article/javascript-101-1

This tutorial provides an introduction to the basics of JavaScript for the total non-programmer. Some of the techniques in this article aren’t as modern as the alternatives we’ve presented here, nonetheless you’ll get a good feel for the JavaScript language itself.


www.quirksmode.org

Freelance web developer Peter-Paul Koch’s list of CSS and JavaScript techniques and scripts covers a considerable amount of useful ground in this area.




A simple JavaScript example


Here’s a simple piece of JavaScript that converts a text field’s value to uppercase when the user tabs out of the field. First let’s see the old, bad way of doing it:


<input id=”street” type=”text” onchange=”this.value = this.value.toUpperCase();”>


Here we’ll recommend a more modern technique. First, the HTML:


<input id=”street” type=”text”>


Second, the JavaScript, which is usually located in the <head> part of the page:


<script type=”text/javascript”>

function uppercaseListener() {

this.value = this.value.toUpperCase();

}

function installListeners() {

var element = document.getElementById(‘street’);

element.addEventListener(‘change’, uppercaseListener,

false);

}

window.addEventListener(‘load’, installListeners, false);

</script>


The first function does the work of converting the text. The second function makes sure that the first is connected to the right HTML tag. The final line performs this connection once the page has loaded in full. Although this means more code, notice how it keeps the HTML content clean and simple.


Get some tools!


A good JavaScript development environment makes working with JavaScript far easier than it would otherwise be. Testing pages in Internet Explorer (IE) can leave something to be desired; if your page generates JavaScript errors, IE isn’t likely to be very helpful at diagnosing where, or what, they are. The most useful, yet simple, tool for JavaScript debugging is the JavaScript Console in Mozilla or Mozilla Firefox. This console will clearly display where any JavaScript error occurs on your page, and what that error is. Mozilla Firefox works on virtually all platforms, and it’s not a big download. It also offers better support for CSS than Internet Explorer, and should be part of your development toolkit. Beyond this, there’s also the JavaScript debugger in Mozilla, which is named Venkman. It can be useful, but be aware that it takes a bit of setting up. In practice, though, when you’re enhancing your site with DHTML, you don’t need anything as complex as a debugger; the JavaScript Console and judicious use of alert statements to identify what’s going on will help you through almost every situation.


Another tool that’s useful is a good code editor in which to write your website. Syntax highlighting for JavaScript is a really handy feature; it makes your code easier to read while you’re writing it, and quickly alerts you when you leave out a bracket or a quote. A good editor will seriously speed up your coding work. Plenty of powerful, customisable editors are available for free. But, if you’re currently writing code in Windows Notepad, have a look at what else is available to see if any other product offers an environment that’s more to your liking. You’ll want syntax highlighting, as already mentioned; a way to tie in the external validation of your pages is also useful. Textpad and Crimson Editor are Windowsbased editors that cover the basics if you’re developing on a Windows platform; Mac users tend to swear by BBEdit; Linux users have gedit or Kate or vim to do the basics, and there’s always Emacs. JavaScript is the engine on which DHTML runs. DHTML focuses on manipulating your HTML and CSS to make your page do what the user wants, and it’s JavaScript that effects that manipulation. This article outlines the very basic building blocks of DHTML. Read DHTML Utopia: Modern Web Design Using JavaScript & DOM by Stuart Langridge (www. sitepoint.com) and discover the basic techniques you can use to start making your websites dynamic, plus advanced scripting techniques for building menus, forms and even whole dynamic web applications.


About the author


Stuart Langridge has been playing with the web since 1994, and is quite possibly the only person in the world to have a BSc in Computer Science and Philosophy. He invented the term ‘unobtrusive DHTML,’ and has been a leader in the quest to popularise this new approach to scripting. When not working on the web, he’s a keen Linux user and part of the team at open-source radio show LUGRadio. He likes drinking decent beers, studying stone circles and other ancient phenomena, and trying to learn the piano. Stuart contributes to Stylish Scripting: SitePoint’s DHTML and CSS Blog.

Building a Web Site Poll Using Ajax

Paul Hudson reveals how to add a poll to your pages using AJAX power


Just when you thought it was safe to open your web browser, JavaScript is back with a vengeance. Admit it: when you moved from clientside to serverside programming, you breathed a sigh of relief at leaving cross-browser problems, broken scripting implementations and technology acronyms behind. But now that web site back-ends have been revolutionised through powerful new scripting languages, it’s time to focus on the front end.


AJAX – in case you didn’t see our feature last issue, is an acronym for Asynchronous JavaScript and XML – is about eliminating the lack of interactivity that we’ve all grown used to on the web. If you have a document that may change while a user is viewing it (an email inbox, for example), then you would normally have had to set a HTML meta tag to refresh every minute, or force users to click Refresh by hand. With AJAX, we can program the page to ping a server to check for updates, download any new information and insert it into the page.



Nothing about AJAX is new: XML has been around for several years and JavaScript for longer. The difference is that a special JavaScript object, known as XMLHttpRequest, is being bound by JavaScript and used to send and receive XML. This object isn’t new either, but has only started to see proper use with AJAX.


To check whether a page has changed, our HTML page calls a JavaScript function that sends off an XML request to our server. This is processed and a response is sent back in XML saying what has changed. PHP fits into the AJAX equation as the serverside parsing mechanism: it accepts the client XML, runs the necessary database checks, and sends the results back down to the client. This close interrelationship of languages means you need to be up to scratch not only on PHP, but also on JavaScript and XML.


Copy the code:

We are going to take you through a very basic example of AJAX code with the aim of creating a web poll that will enable your site users to vote on an issue:


Our mission this issue is to produce an AJAX web poll using PHP, MySQL, JavaScript and good old HTML. Once you’re more proficient with AJAX you’ll see there are many ways of doing the same thing, including lots of shortcuts. Take your time: learn the standard way of doing things first, then cut corners later! For this code to work, you need to choose a relatively modern web browser: Safari 1.2, Firefox 1.5, IE 6 and other browsers of that level are all AJAX-ready.


1. The first thing we’re going to look at is how to create an instance of the XMLHttpRequest (XMLHR) object. Surprisingly enough, this was invented by Microsoft back in the IE5 days, and was implemented as an ActiveX object. Most other web browsers don’t use the ActiveX system for embedding objects into pages, so they have their own method of creating an XMLHR object. Fortunately, IE7 (due out in Windows Vista) will drop the ActiveX method and switch to the de facto standard used by other browsers. Until then, we need to write a function that detects the browser and creates the object in the correct way. Save this in ajax.js:


function createAjax() {

var ajax = false;

if(window.XMLHttpRequest) {

ajax = new XMLHttpRequest

();

} else if(window.ActiveX

Object) {

ajax = new ActiveXObject

(“Microsoft.XMLHTTP”);

}

return ajax;

}


This will create an XMLHttpRequest on any modern browser, as long as the IE browser has ActiveX enabled.


2. We can now go ahead and write a script that creates a new XMLHR object with the createAjax() function, then requests content from our server and loads it into the page. The full code to do this is in the index. php files in directory 2 of the PHP tutorial file on the CD, but we want to explain what these important lines do:


var http = createAjax();

if (http) {

http.open( get , check.

php );

http.onreadystatechange =

handleResponse;

}

function handleResponse() {

if (isAjaxReady(http)) {

response = http.response

Text;

document.getElementById

( mycontent ).innerHTML

= response;

}

}


When we’ve created our object and made sure it’s working, then call its open() function. This tells our XMLHR object what HTTP method it should use (get, rather than post or head) and what file it should request (check.php). We also set its ‘onreadystatechanged’ property to be ‘handleResponse’, which means that when the ready state (the current state of our XMLHR object) is changed, the handleResponse() function will be called. The ready state changes when the object is doing something, such as sending data or receiving data. By attaching ourselves to this state change, it’s possible for us to monitor what it’s up to and catch when it’s received some data.


The handleResponse() function gets called whenever the state of our XMLHR object changes. The first thing that happens is a call to the isAjaxReady() function, which we’ve added to your ajax.js file. The XMLHR object has several states: zero is uninitialised, one is loading, two is loaded, and so on. What we care about is state four, which means finished, and is used when the XMLHR object has sent its data and received a response back from the server. The isAjaxReady() function is just a quick one-liner to check whether the XMLHR object is in state four, and returns true if that’s the case.


If we’re in state four, then we’re able to read the response we got back from the server and print it out. In index.php you’ll see there’s a DIV with the ID ‘mycontent’. This is where the output from the XMLHR object gets stored. The request itself just loads check.php, which, if you look on your CD, you’ll see that it contains a call to phpinfo() to send back a lot of HTML. If everything has worked as it should, you’ll be able to see it embedded inside index.php thanks to AJAX.


3.Receiving some text and printing it out is hardly interesting and not at all useful, but AJAX can do so much more. If you look in the directory 3 on this issue’s CD you’ll see the file sql.txt. Take the SQL from there and insert it into a database server, because we’re now going to have our PHP script read that data, convert it into XML, send it across the web to our XMLHR object, then parse and display it using JavaScript. There are two interesting code sections to examine here. The first is check.php, which is now useful:


<?php

header(“Content-type: text/

xml”);

mysql_connect(“localhost”,

“dotnet”, “blabla69”);

mysql_select_db(“dotnet”);

$result = mysql_query

(“SELECT Question, Answer1,

Answer2, Answer3, Votes1,

Votes2, Votes3 FROM poll

ORDER BY ID DESC LIMIT

1;”);

extract(mysql_fetch_assoc

($result), EXTR_PREFIX_ALL,

“vote”);

echo “<vote>”;

echo “<question>$vote_

Question</question>”;

echo “<answer><value>$vote_

Answer1</value><votes>$vote

_Votes1</votes></answer>”;

echo “<answer><value>$vote_

Answer2</value><votes>$vote

_Votes2</votes></answer>”;

echo “<answer><value>$vote_

Answer3</value><votes>$vote

_Votes3</votes></answer>”;

echo “</vote>”;

?>


4. You’ll need to edit the MySQL connection data to work on your local system. The call to mysql_query() loads the most recent poll in your database, which is extracted and set inside some basic XML. There’s no DTD, which means there’s little point trying to reference elements by IDs because XML has, as yet, no innate knowledge of what an ID is, unlike HTML and XHTML. The second piece of interesting code is in index.php, which has now been upgraded to handle XML rather than plain text:


var response = http.response

XML;

pollQuestion = response.get

ElementsByTagName( question )

[0];

pollAnswers = response.get

ElementsByTagName( answer );

pollAnswerText = “”;

for (i = 0; i < pollAnswers.

length; ++i) {

pollAnswerValue = pollAnsw

ers[i].getElementsByTagName

( value )[0].firstChild.

data;

pollAnswerVotes = poll

Answers[i].getElementsByTag

Name( votes )[0].firstChild

.data;

pollAnswerText += <input

type=”radio” name=”vote”

value=” + (i + 1) + ” />

+ pollAnswerValue + “ (“ +

pollAnswerVotes + “)<br

/>”;

}

new_html = <form method=

”post” action=”vote.php”

><strong>Question: ;

new_html += pollQuestion.

firstChild.data + :</strong>

<br /> + pollAnswerText;

new_html += <input type=

”submit” value=”Vote!” /></

form> ;

document.getElementById( mycon

tent ).innerHTML = new_html;


The first line contains a subtle but important difference: we’re not using http.response any more, but http.responseXML instead, which gives us an object to work with rather than a text string. This object is quite difficult to use, precisely because the lack of IDs for direct reference mean we have to pull out tags by name using getElementsByTagName(), then refer to the first item in that array (the [0] part), even if there’s only one such element in the XML.


Most of the code is there to pull values from the XML (specifically the question and answer tags) and convert them into an HTML form where users can submit their answer. This form is set up to be sent to vote.php, which means that we’re using AJAX to read the data but plain old HTML forms to submit the data.


Of course, if we’re going to do an AJAX web poll we ought to go the whole hog and send and receive data. The code for this is in directory 4 on your CD, and you’ll see that check.php is still there to read the vote data, but there’s now also vote.php, which saves votes back to the database. There’s a minor change in check.php: the <vote> element now has an ID attribute so we know which poll people were voting in. As mentioned already, this isn’t the same as the HTML/XHTML ID attribute that can be used to identify elements uniquely; instead, this is just a data field, like anything else.


The index.php file has also been upgraded somewhat, because we now need to make two calls through XMLHR: one to read the poll, and another to write our vote. It’s not tricky to re-use XMLHR objects for multiple requests, but when you’re learning it’s easiest just to keep a clear separation between XML requests. As a result, in the code you’ll see that loadVote() creates an XMLHR object, doPollRead() retrieves the data, handlePollRead() parses the XML and displays it, and doVoteWrite() creates a fresh XMLHR object and submits the vote. It also re-calls loadVote() and doPollRead() so that the poll updates once you’ve voted.


The only other part of the code that needs any explanation in the new index.php is the following section:


for (i = 0; i < vote_options.

length; ++i) {

if (vote_options[i].checked

) item_selected = i + 1;

}

if (http) {

http.open( get , vote.

php?Vote= + pollID + &

Answer= + item_selected);

}


The first part loops through our vote radio buttons and finds the one that’s selected. Note that we add one because JavaScript arrays are zero-based whereas out database fields are Votes1, Votes2 and Votes3. The second part is where we send our selection over to vote.php using the HTTP GET method. This requires us to separate our URL from our data with a question mark, and also to separate each field with ampersands, as per normal.


We’ve only had space to cover the absolute core parts of the AJAX code here – to learn more, read the code on your CD.