CSS, JavaScript and XHTML Explained

Estelle Weyl’s Blog of quirks, random thoughts and funky finds discovered in day-to-day coding

 

Web Developer Interview Questions May 27, 2007

Filed under: Web Development — Estelle Weyl @ 4:31 pm


Web Developer Interview Questions:

The main technologies required for a web developer are CSS, HTML and JavaScript. A good web developer also needs to have a grasp of and interest in both web standards and accessibility. While most web developer roles require other technologies such as Unix, Apache and server management, MySQL & PHP or SQL & ColdFusion or other dB and programming technologies, CVS, Perforce, or other source control management interfaces, I am only going to cover the technologies that span all Web Developer job descriptions: HTML, Web Standards and Accessibility, CSS and JavaScript.

The main skill I look for in a web developer is intelligence*, a desire to learn and an adoration of web standards. These questions target knowledge rather than capacity to learn. So, for each question remove 2 points if the answer, whether correct or not, sounded like it was quoted from a text book or this blog entry (unless, of course, you are interviewing me). Add points for interviewee efficient thought processes: if they didn’t know the answer to start with but figured it out in the end.

Please have a look at Web Developer Resume Screening for thought on how to filter through resumes to find good Web Developer applicants.

* Note: Intelligence ≠ Education. A Masters or PhD may just mean that they had the time and money to delay getting a job. Look for people who can think, not ones who regurgitate text books.

Please note that these questions are two years old.
… and … quoting @seldo: “I am adding ‘Can you use the men’s room without peeing all over the floor?’ to my list of phone screen interview questions.” Generally not necessary if interviewing women.

XHTML, CSS & JavaScript Web Developer Applicant Questions

XHTML Web Standards Interview Question

Question:

What is a DTD? What DTD do you generally use? Why? Pros and cons.

Answer

See the bottom half of DTD: the Document Type Declaration

Answer Rating:

  1. Completely wrong answer though pretends to know it
  2. I don’t know (I give points for honesty), trying unsuccessfully but honestly to give the right answer
  3. Knowledge of the definition, but doesn’t know why they are used.
  4. Knowledge of which one to use and why
  5. Explanation of Quirks mode versus Regular mode and analysis of which one is best for different media

Accessibility Interview Question

Question

Tell me some considerations in selecting font size?

Answer

Font sizes should be declared using relative measurement values, such as ems, via a style sheet, without the use of the term !important. There are issues with browser font size enlarging which can be rectified via CSS.

Answer Rating

  1. uses <font> tag
  2. Gives an answer using pixels using CSS
  3. Explains that font size should be declared using relative font sizes
  4. Explains that font size should be declared using ems or percentages
  5. Gives the answer above

CSS Interview Question

Question

a) What are the possible values for the display attribute that are supported by all browsers?
b) What is the default value for the display attribute for the image element? (what is the difference between inline and block level elements)
c)What does display: run-in do?
d) Difference between “visibility:hidden” and “display:none”? What are the pros and cons of using display:none?

Answer

main values: none, block, inline, list-item, run-in
all values: inline | block | list-item | run-in | compact | marker | table | inline-table | table-row-group | table-header-group | table-footer-group | table-row | table-column-group | table-column | table-cell | table-caption | none | inherit
default value: inline, block or list-item, depending on the element. The <img> is an inline element.
Run-in should make the run-in element be the first line of the next sibling block level element, if it is before a block level element that is not floated or absolutely positioned. If the next sibling is positioned or floated, then the run-in element will be a block level element instead of appearing in-line.
PPK’s Quirksmode explains it well. The w3schools lists table display values.
When visibility is set to hidden, the element being hidden still occupies its same place in the layout of the page. If the display is set to none, the element does not occupy any space on the page — as if it didn’t exist..

Answer Rating

  1. Doesn’t know
  2. Knows the answer to A
  3. Knows the answer to A and D
  4. Knows the answer to A, B and D
  5. Knows the answer to C too!

CSS Interview Question

Question

a) What are the five possible values for “position”?
b) What is the default/initial value for “position”?
c) How does the browser determine where to place positioned elements
d) What are the pros and cons of using absolute positioning?
e) if they are really advanced, ask about IE z-index issues with positioned elements.

Answer

a) Values for position: static, relative, absolute, fixed, inherit
b) Static
c) They are placed relative to the next parent element that has absolute or relative value declared
d) Absolutely positioned elements are removed from the document flow. The positioned element does not flow around the content of other elements, nor does their content flow around the positioned element. An absolutely positioned element may overlap other elements, or be overlapped by them.
e) IE treats a position like a z-index reset, so you have to declare position of static on the parent element containing the z-indexed elements to have them responsd to z-index correctly.

Answer Rating

  1. Doesn’t know
  2. Knows 4 out of 5 answers in part A
  3. Knows A & B
  4. Knows A, B & C
  5. Knows A-D
  6. Knows E too

CSS Interview Question

Question:

Write a snippet of CSS that will display a paragraph in blue in older browsers, red in newer browsers, green in IE6 and black in IE7

Possible Answer:

#content p{color:blue}
html>body #content p {color:red}
* html #content p{color:green}
html>body #content p {*color:black;}

Answer Rating

  1. Doesn’t know
  2. Knows how to declare one color, but no hacks
  3. knows the html>body hack and * html hack
  4. Knows all the hacks, but doesn’t validate or uses conditional comments in the HTML
  5. Gives you the right answer and explains why the CSS won’t validate, or, uses a valid hack, other than conditional IE comments, instead of the above answer.

Basic Javascript Interview Question

Question:

What is the correct way to include JavaScript into your HTML?

Answer:

See Including Javascript in XHTML for answers.

Answer Rating:

  1. <a href=”javscript:function()”> - and other incorrect answers
  2. verbally explains the theory but doesn’t know how to do it
  3. correct explanation using inline event handlers or inline code
  4. discusses and knows how to implement javascript event listeners
  5. Explainst how you include JS within an XHTML document and ensure it validates using CDATA, explains

Basic Javascript Array / XHTML Form Interview Question

Question

Are the following all equal, and, if so, what would your code look like to make the following all equal the same thing:

  alert(document.forms["myform"].elements["field"].value);
  alert(document.forms[1].elements[1].value);
  alert(document.myform.field.value);

answer:

<form name="myform" method="post" action="something">
<input name="anything" value="anything" type="something" />
<input name="field" value="something" type="something" />
</form>

Answer includes knowing that the form is the second form on the page, and that the field input element is the second element within that form.

Answer Rating

  1. Doesn’t know how to code forms and doesn’t know that the first index of an array is 0.
  2. Knows either how to code forms with valid XHTML or that array starts at 0, but not both.
  3. Knows how to code forms but not correctly, but omits something like doesn’t know that the form needs to be the second one on the page, and the element is the second one in the form. Would know how to do it if they actually put thought into it.
  4. Codes the form correctly, but uses ID instead of name
  5. Codes everything correctly

JavaScript Interview Question

Question:

How do you dynamically add a paragraph with stylized content to a page?

Possible Answer:

newParagraph = document.createElement('p');
newParagraph.setAttribute('class', 'myClass');
newText = document.createTextNode('this is a new paragraph');
newParagraph.appendChild(newText);
myLocation = document.getElementById('parent_of_new_paragraph);
myLocation.appendChild(newParagraph);

Answer Rating:

  1. Wrong Answer (i.e. “you can’t”), I don’t know.
  2. Use JavaScript, with no knowledge or incomplete knowledge of how that is done. Suggesting innerHTML, but not really knowing. Or explanation of accessibilty issues surrounding this.
  3. Able to explain how you create a node, add content to the node, add a class attributes to that element, and then add that node as a child of the parent element (the above example)
  4. Explanation of how to do it (worth 3 points) and explanation as to issues that arise when doing it, such as screen readers not knowing that text has changed, IE6 and IE7 not applying styles included with added content, not duplicating IDs, etc.
  5. Has no clue how to do it to start, but can figure it out with guidance: extra points for the quick learner!

Other questions ideas:

Q: How do you organize your CSS? How do you come up with id and class names (what naming conventions do you use)?
A: While there are no right answers, there are best practices. Issues to look for are not having div mania, no inline CSS, no presentational markup, minimal use of classes, understanding the CSS cascade.

Q: What do you think of hacks? When should you use them? If you use them, how do you maintain them? What can be done to avoid needing to use box-model hacks? (if they aren’t pros, you can ask them what is the issue with x-browsers and the box model)

Q: What are the pros and cons of using tables for layout? Do you use tables? What are the pros and cons of tableless design? How do you generally layout your pages?
A: check for them NOT using tables

Q: Check to ensure that they separate structure and semantics first from presentation later? Do not ask about this during HTML, but do in webstandards.

Q: What are some deprecated elements and attributes that you use, and in what instances do you use them?
A: List of deprecated elements and attributes.

Q: What is involved in making a website accessible? What are arguments you use to convince others to invest in making their web site accessible.
A: See Making the web Accessible. Making sites accessible also makes them more search engine friendly (saves money), makes your pages accessible to the 20% of the population that has some type of disability (so you can make more money) and it’s the law in many places.

Q: Define what web standards mean to you? How do you implement web standards?

Q: In CSS, how can you make a form elments background-color change when the user is entering text? will this work in all browsers?

Q: How can you target an element in your HTML using the DOM?


 
 

Web Developer Resume Screening May 26, 2007

Filed under: Web Development — Estelle Weyl @ 7:02 pm

How to filter through resumes to find good Web Developer applicants

What makes a good web developer these days? An alphabet soup of skills that are simply an effort at search engine optimization for Monster.com, HotJobs or Dice? Don’t waste your time and the applicant’s time by bringing them in for a three hour interview unless you know there is a chance of a good match. Do a phone screen first. It will save you a lot of time and frustration. Before you call, however, you should review not only their resume, but their portfolio of work as well.

Web Developer Resume & Portfolio Screening

When reviewing a resume, use the resume as a guideline of possible skills, not gospel. In deciding who to interview and when to pass, check the resume for stated skills and match that skill set with the skill set displayed in a review of the sites the applicant coded. An understated resume that shows matching skills should be considered as much, if not more, than an overstated resume that shows those same skills. Don’t think a woman is less qualified than a man simply because her resume is modest because his may in fact be exaggerated.

The question has to be, "does the person know how to code correctly?" In reviewing an applicants portfolio there are certain indicators that display whether or not the applicant knows what they are talking about.

  • Elements coded in capital letters or mixed syntax
    <P><A Href="Link.html">Click me</a></P>
    Skip this candidate
    correct: <p><a href="link.html">Click me</a></p>
  • Overlapping elements
    <strong>Hi, my name is <em>estelle</strong></em>
    If it happens once, and otherwise the candidate looks good, it may show a sloppy error, but otherwise the applicant may know how to code.. If the code generally looks like the above, get the shredder!
    correct: <strong>Hi, my name is <em>estelle</em></strong>
  • Gratuitous use of table layouts, frames and flash navigation
    <table><tr><td>&bull;</td><td>should be a list</td></tr></table>
    If the applicant shows no samples of semantic navigation, or displays no samples of tableless layout, then take a look at your other applicants.  If generally everything is semantic, with little exceptions, consider the applicant’s client: sometimes clients insist on development methods. If it’s common, then the applicant doesn’t understand semantic markup and you should pass.
    correct: <ul><li>should be a list</li></ul>
  • Sloppy, pointless CSS
    a {text-align: left; margin: 10px;} // links are default inline elements.
    Take a look at the CSS, not just the HTML. You will likely find errors. The erroneous application of margin on an inline element if it occurs once may be the sloppiness of not cleaning up code or leaving in some CSS from a previous element.  If the style sheet shows a lack of understanding the difference between inline and block elements, doesn’t grasp positioning or floating, move on. If they really know CSS, and they are just sloppy with small clients, then keep reviewing the candidate. If they are both sloppy and have limited knowledge, you can find better.
    better: a {display: block; float: left; margin: 10px;}
  • Abuse of inline javascript event handlers
    <a href="javascript:void()" onmouseover="document.images[0].src=’on.gif’" onmouseout="document.images[0].src=’off.gif’"><img … /></a>
    Give bonus points to those who separate behavior (javascript) from structure (html). Take away points (or throw out the resume) or those who use links for presentation, as in the above sample.
    Separating behavior and structure can be taught. But, in the example above could have been done purely with css. If that is the crap they display, toss their resume: they are not even trying. If you see multiple href="#", or href="javascript:void()", then Next!
    better: <div id="myImg"><img ... /></div> with the content and background controlled via CSS
  • Missing doctypes, two xml prologs, conflicting encoding (xml prolog and meta charset)
    <html><head><title>Untitled Document</title></head>
    Value an applicant who declares the wrong doctype over one who doesn’t declare a doctype at all. Value an applicant who declares an inappropriate charset over one who doesn’t declare a character set. The right answer can be taught more easily that teaching someone to care about web standards.
  • Non-breaking space and br alignments
    <br />&nbsp;<br />&nbsp;
    Web developers should be held completely responsible for the shell of their pages: the templates. In shell of page, using markup for presentation means the applicant isn’t trying to code well. If you find this coding style in the content of the page, and not the guts and the template portion of the site is correctly coded, assume they know how to code and that their client is responsible for the poor content maintenance. Clients will update their own content, and they do the screwiest things.
  • Overreliance of WYSIWYG Editors
    .style1 {color: #ff0000;}
    .style2 {color: #ff0000; font-weight: bold;}

    There is nothing wrong with using Dreamweaver, but you don’t want to hire someone who relies on it. If all javascript functions in the applicants code start with MM, such as MM_showHideLayers, or styles are named in order from style1, style2 .... style65, then they are using Dreamweaver as a crutch and don’t actually know how to code CSS or JavaScript (and perhaps not even XHTML).

Valid Excuses for Samples of Questionable Code

  • Client’s Budget:
    When looking at a sample of code, consider who the site is for. If the site is for a large corporation with funding, be a little stricter in analyzing the code. If the site is built for a small client on a pay per hour basis, consider being a little more lenient. When building sites for small clients, developers may cut corners a few ways to save them money. For example, they may not spend the time cleaning up or commenting the CSS. While you may want to pass on someone who repeats "text-align: left;" 16 times, since it should have been set as the outer element, don’t hold someone who puts three extraneous "text-align: right;"s at major fault.
  • UED or Designer Specifications may have been questionable :
    I coded a site for a designer who created a different layout for the content of every page. While I used an external style sheet for the shell of the page, I used inline styles for the wacky positioning of images within the page. While I should have removed inline styles and create classes, the classes would never have been re-used, the client was on a budget and the graphic designer was going to have me move the images around anyhow.  Your applicant may have similar clients.  I thought it best not to spend my time or the client’s money cleaning up the CSS.
  • Someone else is maintaining the content:
    Sometimes clients maintain their content which can be the cause of bad code. In the shell of the document (the template), if there is mixed case XHTML that’s bad since that is most likely definitely the developers mark. However, if the template code looks great, and only the content is coded like crap, give the applicant the benefit of the doubt.  Perhaps it was being maintained by the client rather than the coder. You may find some mso=normal’s (don’t you love microsoft), unclosed <p> and <li> in the code. These may be signs that the applicant’s clients are maintaining their own pages or using CMS. One of my sites has a table layout for the home page since I was unable to get the client to understand that WYSIWYG editors render pages differently than actual browsers.  Other than the home page the site is well coded, but that home page currently has 30 instances of <p style="margin:0; padding: 0;">&nbsp;</p>.
  • Useless Flash and other Tacky Design elements:
    Sometimes clients insist on flash navigation or intros. If the applicant’s portfolio samples all have flash navigation and few or no samples of semantic navigation, skip the candidate. However, if a few of their sites have flash intros or navs, but it’s evident that they know how to do a standards compliant unordered list navigation from other sites, then don’t hold a flash component against the applicant.

In conclusion, if someone obviously doesn’t know what they’re doing, don’t bother interviewing them. However, if the only crap code you see is the html of their portfolio ("the cobbler’s children have no shoes"), and they show some examples that show that they can definitely be up to par, then do a phone screen.

Note: See also my list of interview questions for web developers.

 
 

IE7 only CSS hacks: Examples May 21, 2007

Filed under: CSS (including hacks), IE7, Web Development — Estelle Weyl @ 12:56 am

Examples of Hacks described in IE7 only CSS Hacks: Explained

This blog entry is the companion page to IE7 only CSS Hacks: Explained which elaborates on how and why these hacks work. Feel free to open this page up in IE7, IE6, Opera and Firefox on the PC, and Safari and Opera on the Mac.


</p> <div lang="en" align="left"> <!-- useless comment --></p> <div> <h2>The Star(*) hack</h2> <p class="starHack">body>div .myClass { *color: #CC33CC; }</p> <h2>The conditional comment</h2> <p class="conditional"> &lt;!&#8211;[if IE 7]&gt;<br /> &lt;style type=&quot;text/css&quot;&gt;<br /> p.conditional {color: #CC33CC;}<br /> &lt;/style&gt;<br /> &lt;![endif]&#8211;&gt;</p> <h2>The LANG filter</h2> <p class="item">.item {color: #000000;}<br /> html&gt;div .item {color: #CC33CC;}<br /> *:lang(en) .item{color: #666666;}<br /> .item:empty {color: #666666 !important} </p> <p>&lt;div lang=&quot;en&quot;&gt;<br /> &lt;p class=&quot;item&quot;&gt;<br /> This will purple in IE7, grey in Firefox and black in IE6</p> <h2>Triple X Hack</h2> <p class="testx" id="testy">.testx { color: #000000; }<br /> p[id$=&quot;testy&quot;] { color:#cc33cc; }<br /> p[id$=&quot;testy&quot;]:not([class=&quot;xxx&quot;]) { color:#666666; }<br /> @media all and (min-width:0px) { p[id$=&quot;testy&quot;] { color:#aaaaaa; } }</p> <p>This will purple in IE7, grey in Firefox and black in IE6</p> <h2 id="case">The Case Sensitive Attribute Hack</h2> <p class="casesensitive">p.casesensitive {color: #000000;} <br /> div[align~=left] p.casesensitive {color: #cc33cc;}<br /> <br /> div[align~=LEFT] p.casesensitive {color: #666666;} </p> <p class="casesensitive">&lt;div align=&quot;left&quot;&gt; &lt;p class=&quot;casesensitive&quot;&gt;<br /> This will purple in IE7, grey in Firefox and black in IE6&lt;/p&gt;</p> <h2>Aimsterloo Hack<br /> a.k.a.<br /> First Child Comment Hack</h2> <p class="fchild">p.fchild {color: #000000;}<br /> html&gt;div p.fchild {<span class="casesensitive">color: #cc33cc;</span>}<br /> div :first-child p.fchild {color: #666666;} </p> <p>&lt;div&gt;&lt;!&#8211; useless comment &#8211;&gt;&lt;div&gt;&lt;p class=&quot;fchild&quot;&gt;<br /> The div should be the first child of the div, but in IE it isn&#8217;t&#8230; </p> </div> </div> <p>

 
 

Beginning AJAX using the YUI Library May 19, 2007

Filed under: AJAX, JavaScript, Web Development — Estelle Weyl @ 6:15 pm

This is a real into level tutorial. The target audience for this entry is people who find http://developer.yahoo.com/ a bit overwhelming. If you think it’s a cinch, this will be below your level. If you want a more detailed intro than what they have on the YUI site, then continue on.


Preparation Step:
Create a text file and save it at include.html. Include some basic html in this page.

<h1>Hello World</h1>
<p>This is my first AJAX call</p>

Now, let’s set up our first AJAX web page using the YUI library. Our page will simply include the content from include.html when a button is pressed. Let’s begin….

Step 1: Start a new XHTML document with a typical template:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>My First Ajax using the YUI Library</title>
</head>
<body>
</body>
</html>

Step 2: Adding script calls to include the YUI library components we will be using.

<script src="http://yui.yahooapis.com/2.2.2/build/yahoo/yahoo-min.js"
   type="text/javascript"></script>
<script src="http://yui.yahooapis.com/2.2.2/build/connection/connection-min.js"
   type="text/javascript"></script> 

Notes:

  • As we discussed in the earlier blog entry "Including Javascript in XHTML , you must include the type attribute, but do not include the language attribute.
  • While in production you should put these calls at the end of your body, for this exercise, go ahead and put these in your header (after the meta character type and the title).
  • These scripts include minimized versions of the YUI library. Minimized means that the code base was minimized, with extra characters, comments and spacing removed. This makes the file smaller so the bandwidth is less, but it makes it human un-readable. The full version can be downloaded from The YUI distribution library.

Step 3: Create a <div> with an id in the body of your page and a link that will call the AJAX function. The div will be filled with the response from our AJAX call. Include an onclick event handler in the link. There will be another tutorial soon on using the YUI event utility to dynamically include event handers (separating presentation from the content). Make sure that the link’s href leads to a real page. Web standards and accessibility guidelines state that all links should really be links!

<div id="mydiv>
</div>
<p><a href="/include.html" onclick="callAJAX(); return false;">
    My first AJAX</a></p>

Step 4: Add a script tag to your page. This is where we are going to put all the javascript AJAX functionality

<script type="text/javascript">
  //<![CDATA[  		

  //]]>
</script>

This is what we have thus far:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>My First Ajax using the YUI Library</title>
<script src="http://yui.yahooapis.com/2.2.2/build/yahoo/yahoo-min.js" type="text/javascript"></script>
<script src="http://yui.yahooapis.com/2.2.2/build/connection/connection-min.js" type="text/javascript"></script>
</head>
<body>
<div id="mydiv">
</div>
<p><a href="/include.html" onclick="">My first AJAX</a></p>

<script type="text/javascript">
//<![CDATA[

//]]>
</script>
</body>
</html>

Save your file as myfirstajax.html. The script we write will be added between the CDATA open and closing tag. For more on why we use CDATA, refer to the entry on how to Include Javascript in XHTML. If you prefer, you can make a single external javascript call and add everything to that external file. If you open it up in a browser all you should see in one link that reads "My first Ajax". The page should validate.

Step 5: Add the YUI Connection Manager utility line of code that initiates an asynchronous transaction. Put this line of code in your javascript:

var transaction = YAHOO.util.Connect.asyncRequest('GET', sUrl, callback, null);

Explanation:

  • The YAHOO.util.Connect.asyncRequest method starts an XMLHttpRequest. It returns a transaction object that has properties that you can use, including status, responseText, responseXML and tId.
  • The first argument is the HTTP method. We will cover POST and GET. The YUI connection manager also supports other HTTP methods, but POST and GET are the most common. Think of the XMLHttpRequest as a form submission: choose the HTTP method the same way you would choose a form submission method.
  • The second argument is the URL to which you are submitting the XMLHttpRequest. Think of it as a form action. It is the response page we are requesting.
  • callback, the third argument, is a series of functions that we will define to handle the server response.
  • The fourth argument is only used if the first method is 'POST'. Since we are using 'GET', we can set it to null or omit it. If we were using POST, the fourth argument would accomodate our POST message.

Step 6: Define the second parameter: the URL.  The second parameter needs to be set to the URL of the file we want to interact with asynchronously.  In this case we are simply going to include our static page — include.html — created in the preperation step before step 1.

var sUrl = "include.html";

Step 7: Define the third argument: the callback. We’ll add alerts so you can test at this point to see if it works. We’ll replace the success function after we test to see if everything is working thus far. success is the handler code that executes when the XMLHttpRequest is successful. failure is the handler code that executes if the XMLHttpRequest is unsuccessful.

  var callback = {
     success: function(o) {
        alert("AJAX Works"); //SUCCESS
        },
     failure: function(o) {
        alert("AJAX doesn't work"); //FAILURE
     }
  } 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>My First Ajax using the YUI Library</title>
<script src="http://yui.yahooapis.com/2.2.2/build/yahoo/yahoo-min.js" type="text/javascript"></script>
<script src="http://yui.yahooapis.com/2.2.2/build/event/event-min.js" type="text/javascript"></script>
<script src="http://yui.yahooapis.com/2.2.2/build/connection/connection-min.js" type="text/javascript"></script>
</head>
<body>
<div id="mydiv">
</div>
<p><a href="/include.html" onclick="callAJAX(); return false;">My first AJAX</a></p>

<script type="text/javascript">
//<![CDATA[

var sUrl = "include.html";
var callback = {
success: function(o) {
alert("AJAX Works"); //SUCCESS
},
failure: function(o) {
alert("AJAX doesn't work"); //FAILURE
}
}

var transaction = YAHOO.util.Connect.asyncRequest('GET', sUrl, callback, null);

//]]>
</script>
</body>
</html>

Step 8: Save everything and upload both include.html and myfirstajax.html into the same directory on your server. Open http://www.yourserver.com/yourfolder/myfirstajax.html in a browser. If you have an error in your code or didn’t load include.html and myfirstajax.html into the same directory, you’ll get the ""AJAX doesn’t work" alert. If you copy the code in the box above, and uploaded both files correctly into the same directory on your server, you will get the "AJAX Works" alert. If all is good, continue.

Step 9: Our goal for this project is to make the content from your external file
include.html appear on your page. We’ve created a connection to our file. We created a place holder div in step 3 with <div id="mydiv>
</div>
. We are going to target this div, and insert the content from include.html into the div with innerHTML.

Replace

 success: function(o) {
	alert("AJAX Works"); //SUCCESS 
    },

with

 success: function(o) {
    	document.getElementById(’mydiv’).innerHTML =  o.responseText;
    },

The left hand side of the above statement uses the DOM to target the content of mydiv.  The function takes the responseText value of the transaction and replaces mydiv’s innerHTML with the content retrieved by the XMLHttpRequest. Save, upload and test again!

Step 10: The power of AJAX is being able to make a XMLHttpRequest and altering the content of the page once the page is already loaded. Let’s change our code so that instead of loading include.html while we load the page, we load it dynamically when we click on our link. We included the onclick event handler in the link in step 3.  In a future tutorial we will use the YUI event library to dynamically attach an event handler to our link, thereby seperating content from presentation.

Encapsulate the javascript into a function.  Our onclick event handler in step 3 reads <a href="/include.html" onclick="callAJAX(); return false;">, so we will call our function callAJAX().

function callAJAX(){
	var sUrl = "include.html";
	var callback = {
		success: function(o) {
			document.getElementById(’mydiv’).innerHTML =  o.responseText;
			},
		failure: function(o) {
			alert("AJAX doesn’t work"); //FAILURE
			}
		} 

	var transaction = YAHOO.util.Connect.asyncRequest(’GET’, sUrl, callback, null);
} 




The return is included in the eventhandler, so we don’t need to add it to the function. You could also have written the event handler as:

<a href="/include.html" onclick="return callAJAX();">

and added the return to the callAJAX function right before the function close:

 var transaction = YAHOO.util.Connect.asyncRequest('GET', sUrl, callback, null);
	return false;
	}

Test the AJAX file


 
 

Controlling List Item Bullets with CSS - ASCII bullets May 18, 2007

Filed under: CSS (including hacks), Character Entities, Web Development — Estelle Weyl @ 11:08 pm

Using ASCII and UNICODE characters as Bullets with CSS

In non-IE browsers you can stylize lists to have any character as a bullet instead of the default bullet. You will find several sites now using the double right angle quote as a bullet. Many people find the default bullet too large, and prefer to use the middot. Legal documents may find the section symbol (§) useful, and poker players may get a kick out of using spades (♠).

To control the bullet character, you need to remove the default list style, add your character of choice using the :before pseudo-class, add a left margin to indent the entire list item content and provide a negative indentation to make the bullet character that is a part of the first line appear as a bullet.

CSS content does not accept named entities or regular numeric entities such as &#8221;, but does render unicode hexadecimal characters preceded by a backward slash.

Here is sample code:

html>body ul {
    margin: 0;
    padding: 0 0 0 1.2em;
    list-style: none;
    text-indent: -1.2em;
    }

html>body  li {
    margin: 0 0 0 1em;
    }

ul li:before {
    content: "\00BB \0020";
    color: #ff0000;
    font-size: 0.8em;
    }

The content content: "\00BB \0020" above creates a right angle quote appearing as: » followed by a space. There are many other characters that you can use, but this is the most common. For a list of unicode entities check out the list of named HTML entities listed in numeric order. There is a briefer list of named entities in alphabetical order that is a good place to find the entity you are looking for, then got to the numerically ordered entity list which provides more detailed information. If you know the numeric entity, you can also use the CSS Entity Calculator to get the correct code for that character.

The other cool thing is you can stylize the content added content in the :before pseudoclass.

  • list item one
    second line of this first item
  • list item two
  • list item three

The style I used for the above list is:

<style type="text/css">
html>body ul.bulleted {
    margin: 0 0 0 2em;
    padding: 0 0 0 1.2em;
    list-style: none;
    text-indent: -1.2em;
    *text-indent: 0;
    *list-style-type: disc;
    }

html>body ul.bulleted li {
    margin: 0 0 0 1.2em;
    }

ul.bulleted li:before {
    content: "\2666 \a0 \a0 \a0";
    color: #993366;
    font-size: 0.85em;
    line-height:80%;
    }
</style>

Notes:

  • if you notice a double slash (\) in the code above, it really should be a single slash. With FF, the default for <code> thinks I am escaping the next letter, so I had to escape the slash to show the actual code. In some browsers this was an issue, in others it wasn’t. It should only be one slash.
  • As mentioned earlier, IE does not comprehend the :before pseudo-class (see IE7 CSS Selectors: how they fail), but IE7, unlike IE6, does understand html>body so I’ve used the simple star hack to give IE7 back the bullet and IE7 specific margin/padding. You can use any IE7 hack. This was the simplest, but doesn’t validate.
  • See: Creating lists with Images as Bullets using CSS
 
 

Including Javascript in XHTML: external, DOM created, CDATA & comments May 14, 2007

Filed under: Best Practices, JavaScript, Web Development — Estelle Weyl @ 9:57 am

Including Valid External Javascript in XHTML

Correct way to include an external javascript file:

<script src="filename.js" type="text/javascript"></script>
<script src="filename.js" type="text/javascript" charset="utf-8"></script>
  • Even when src is specified, the script tag is not an empty tag, and cannot be written <script src=".... />. If you include the src you should not include any script before the opening and closing tags as browser handling of any script between the tags is not reliable.
  • By convention, the external javascript file should have a .js extension, but this is not required.
  • In XHTML, the type attribute is a required attribute.
  • The language attribute should only be included if the language is not javascript. The browser automatically defaults to the latest version of javascript it supports, so only specify the script language if the languge is something other than the lastest version of javascript. So, include language="vb" if you are including a visual basic script, but don’t include language="javascript1.3" if you are including a javascript file.
  • The charset attribute is optional. Included it (charset="utf-8") if your script includes atypical characters. Omit it if you use only keyboard characters or if you escape your Javascript entity characters..
  • Although you will usually find the script tag in head area, the best place to put it is right before the end of the body. The reason? When the browser encounters a script during page load it ceases downloading from the server. A <script src="url></script> will prevent the download of other page components until the .js file has been retrieved, compiled and executed. Placing the .js at the end of the body can improve both perceived and actual download time. However, if rendering the page requires functions from the javascript, include the javascript before the page calls required functions.
  • The defer attribute – written defer="defer" in XHTML – is a fairly useless attribute of the script tag. It tells the browser that the script does not create any content allowing the browser to defer interpreting the script. The delaying of execution of scripts until after the body content is parsed and rendered is optional for the browser, and the browser still downloads the script, putting download of all other elements on hold, so unless there is a reason to include the script earlier in the page, the recommendation is to place the external script call immediately before the </body>.
  • runat="server" is an optional attribute/value.  I haven’t ever used it, so can’t really comment on it. I assume it’s used for non-javascript scripts and for ASP.net javascripts, telling the server to run the script, or, in the case of any element in ASP.net, on the server.


Including external Javascript by using the DOM

The following onload function appends a javascript file (the source in this case is ‘myjsfile.js’) to your HTML document.

window.onload=function(){
   if(!document.getElementById || !document.createElement){return;}
   var newjs=document.createElement('script');
   newjs.type='text/javascript';
   newjs.src='myjsfile.js';
   document.getElementsByTagName('head')[0].appendChild(newjs);
}

or you can also dynamically add a script to the DOM via a function call:

// loadscript('filepath/myjsfile.js');
function loadScript(src) {
    newjs= document.createElement( "script" );
    newjs.src = src;
    newjs.type='text/javascript';
    head = document.getElementsByTagName( "head" )[0];
    head.appendChild(newjs);
}

Explanation

  • The first line test to see if you browser is ancient and doesn’t accept Javascript
  • The second line creates the the object, but doesn’t add it to the page. The third and fourth lines add properties to our newly created object.
  • The Javascript file only gets added in the last line. We used the DOM to find the parent element for where we want our Javascript file added, and then appended the javascript file object as a child element of the targeted parent element.

Including javascript via a javascript writeln();

I will eventually write the specifics as to why. In the meantime, if you are going to include script within a script by using writeln() — either including a block of code or including an external javascript file — you have to break the opening and closing script tag two parts.

document.write("<scr"+"ipt type=\"text/javascript\" src=\"yoursource.js\"></scr"+"ipt>");

Including Valid Inline Javascript in XHTML

You may notice that your XHTML does not validate because of code in your javascript. Here is the correct way to include an internal javascript file:

<script type="text/javascript">
//<![CDATA[

		code here

//]]>
</script>
  • In XHTML, the type attribute is a required attribute. 
  • Do not include the language attribute, unless you’re including something other than javascript.
  • CDATA is required in XHTML because using the characters <, >, & and " as characters rather than entities will not validate, and Javascript would not understand it if you coded something as if (A &gt; B){}
  • The old fashioned method of hiding the script from browsers of commenting out the javascript, seen on most websites, is useless today as all browsers understand the script tag.  All browsers either support javascript or are smart enough to ignore the content between the script tag if they don’t support javascript:
    <script type="text/javascript">
    <!-- Hiding this way is no longer necessary
    //-->
    </script>
    
  • However, not all browsers support XHTML and therefore may not understand <![CDATA[

        ]]>, so hiding the CDATA from non-XHTML browsers with the single line javascript comment of //, allowes XHTML compliant browsers to except special characters within the CDATA, and non-compliant browsers simply ignore the CDATA call since it’s part of a comment.

  • The best place to put it is right before the end of the body unless rendering the page requires functions from the javascript.


Include valid Javascript eventhandlers in your XHTML

<a href="somevaliddestination.html" onclick="someaction();">

Note: I am working on an entry for adding event handlers/listeners with javascript, which is preferable to inline onclick="someaction();". When done, I will replace this paragraph with a link to that entry.

  • Eventhandlers can be added as attributes to XHTML elements. Like all attributes, the eventhandler should be lowercase. The value, however, is likely case sensitive so case matters, but lowercase is not a requirement.
  • Let links be links. If you are placing an event handler in a link, make sure there is a valid destination for the link.
  • If you need to create an event, but don’t have a valid link destination, then put your event handler in a non-link element such as <span onmouseover="someaction('parameter');">.
  • Like all attribute values, an event handler value should be enclosed in quotes. It is recommended that you use double quotes, since you may need to encapsulate a string in quotes in single quotes within your javascript. Why? You cannot include <![CDATA[ ]]> in an event handler, and you can’t have quotes (") in XHTML that are unescaped. If you need to use quotes inline, use \ before a single quote, and use &quot; within a string. \" will not validate. You cannot use " as it will end your attribute value/javascript eventhandler.
  • Of course, it is best to avoid inline event handlers. Keep your content and your javascript separate: use an external javascript to attach event handlers to your code.

Notes:

  • It is best to use external javascript files!
  • If you are effecting the DOM during page load, and use innerHTML = “string…” after you do it, Internet Explorer erroneously retroactively-prematurely closes the DOM throwing an "Operation Aborted" error. Either avoid using innerHMTL, or don’t modify the DOM until the page is fully loaded (or, better yet, avoid both). See IE and Operation Aborted for more info on this special IE quirk.
  • See also the W3 speccifications for the script in XHTML
 
 

Vertical Centering with CSS May 12, 2007

Filed under: CSS (including hacks), Web Development — Estelle Weyl @ 7:58 pm

Centering Vertically:

There are a few ways to center vertically. In terms of block level elements, the methods are quirky. Inline elements are much simpler to center:

If you know the height of your containing div, and the height of your inner centered div,  or, if you the height of your inner div does not matter, then vertical aligning is simple.  However, if you are vertically centering anything that is variable, such as text, vertical centering is more complex and require hacks.

Note: If you are looking for support for the css property vertical-align, check out the table of CSS properties, values and browser support.

The HTML used in our examples:

<div id="containingBlock">
  <div>
     <p>This sentence will change in each example</p>  </div>
</div>

Note: I will post an entry on vertical centering of text soon

Mathematical Method for known heights:

When you know the height of the containing element, and the height of the element being vertically centered, simply use math to figure out the height of the margins on the inner element.

#containingBlock {display: block; height: 200px;}
#containingBlock div {height:50px; margin: 75px 0;}

The green outlined div is vertically centered in all browsers.

As is evident in the above example, this method really only works for images or other media when you know the exact height of your content. This method should not be used for containing text as a developer really never knows how much text will be contained in the box in the end, and the font size: users should be allowed to increase font size.  In our example, the text does not take up the height alloted to the paragraph, so it is not vertically centered, but the containing div (i made the background grey) is centered..

Block level vertical centering via the table display method:

Vertically centering block level elements should be simple simply by using display: table; and vertical-align: middle.  Unfortunately, IE6 and IE7 do not understand the value of table and table-cell as values of the display property.

The CSS for CSS compliant browsers:

#containingBlock {display: table; height: 200px; position: relative; overflow: hidden;}
#containingBlock div {display: table-cell; vertical-align: middle;}

Rendering of the above code: (borders have been added so you can see the effect, and div id is actually unique) has the anticipated look in Firefox, Safari and other CSS compliant browsers, but not in IE, including IE7.:

Works in FireFox and Opera

The CSS for IE6 and IE7:

#containingBlock {height: 200px; position: relative; overflow: hidden;}
#containingBlock div { position: absolute; top: 50%;}
#containingBlock div p {position: relative; top: -50%;}

Rendering of the above code: (borders have been added so you can see the effect):

Works in IE6 and IE7

The concept is that the outer content which is relatively positioned and has a defined height contains an absolutely positioned div that starts 50% from the top of the container div.  The absolutely positioned div, in turn, contains a relatively positioned element that has as it’s middle the top of the absolutely positioned div.  Look at the colors in IE, and if the above sentence didn’t make sense, it will.

Vertical Alignment Table Display Hack


#containingBlock {display:table; height: 200px; position: relative; overflow: hidden; }
#containingBlock div {*position: absolute; top: 50%; display: table-cell; vertical-align: middle;}
#containingBlock p {*position: relative; top: -50%;}

Works in IE6 and IE7, Firefox, Safari, etc., but doesn’t validate

Vertically Centering Fluid elements within a page (useless, except for useless splash pages):


html, body, #containingBlock {height: 100%; position:relative; }
#containingBlock div {height: 50%; position: absolute; top: 25%; } 		
 
 

IE7 CSS Selectors: How they fail May 8, 2007

Filed under: CSS (including hacks), IE7, Web Development — Estelle Weyl @ 11:52 pm


The following table explains the failures of IE7. I am only listing bugs in IE7 CSS from the selector perspective, not from the rendering perspective. The fact that IE7 fails to heed certain valid CSS selectors will provide opportunity for discovering IE hacks and filters. Quirks in rendering CSS will be posted in a future entry.

Selector IE7 Explanation of issues
*  
E  
.class  
#id  
E F  
E > F  
E + F  
E[attribute] Δ Understands attributes with name value/pairing, but does not understand attributes that are incorrect XHTML.  For example, IE7 understands this selector for attributes such as width="12", or alt="" but does not understand align="" or selected.  So, this can only be used for as a hack if you write non-valid XHTML.
E[attribute=value]  
E[attribute~=value] Δ The quirkiness of IE7 in this case is that it employs some case-sensitivity to the value whether or not the attribute type requires case sensitivity. While it makes sense to compare id values in a case senstive manner, attribute values for HTML are case insensitive. The XHTML specifications state that element and attribute names must be lower case, but it does not say anything about attribute values.  In this case, img[align~=LEFT] will match align="LEFT" but not match align="left" but img[align~=left] will match align="left" and align="LEFT".
E[attribute|=value] Δ IE7 has the same quirkiness as above. In this case, img[align|=LEFT] will match align="LEFT" but not match align="left" but img[align|=left] will match align="left" and align="LEFT".
:first-child Δ

Works in most cases except when the first child is a comment. IE7 treats the comment as the first child, even though CSS specifications state that :first-child should apply to elements, and comments are not an element. Note that there is a space between the selector and the colon. 

div :first-child {font-weight: bold;} will not match the paragraph in:
<div class="happy">
<!–comment –>
<p>Hi</p>
</div>

:link  
:visited  
:lang() Χ IE7 fails completely with this selector, which makes this selector perfect for filtering against IE7.:lang(en) { } should match <div lang='en'></div>, <div lang='EN'></div><div lang='en-US'></div> and even the paragraph in <body lang='en'><p></p></body> because language is inherited.
:before Χ the :before pseudoclass, which in other browsers can be used to insert generated content before an element’s content,fails in IE7.
::before Χ If IE7 can’t handle the :before pseudoclass, did you really think it would understand the double-colon notation of the pseudo-element? See note below for an explanation of the double-colon notation.
:after Χ the :after pseudoclass, which in other browsers can be used to insert generated content after an element’s content,fails in IE7.
::after Χ Likewise, if IE7 doesn’t understand :before, ::before and :after, it won’t understad the double colon pseudo-element after either
:first-letter  
::first-letter Χ

Whereas IE7 recognizes div:first-letter { color:#3333CC;}, it does not recognize div::first-letter { color:#3333CC;}

IE7 seems to have no support for double-colon notation.

:first-line  
::first-line Χ

As in the case of :first-letter, IE7 recognizes div:first-line { color:#3333CC;} but does not recognize div::first-line { color:#3333CC;}

Substring matching attribute selectors
E[attribute^=value] Χ IE7 doesn’t understand the concept of "substring" matching. The CSS specifications state that the E element whose attribute value begins exactly with the string listed in the value should be matched.  IE7 only understands exact matches for the entire value. IE7 respects the attribute values that should be case sensitive.
E[attribute$=value] Χ The CSS specifications state that the E element whose attribute value ends exactly with the string listed in the value should be matched.  IE7 only understands exact matches for the entire value.  See the attribute above.
E[attribute*=value] Χ Represents an element with the att attribute whose value contains at least one instance of the substring "val".
E ~ F  
:root Χ This should match HTML, since HTML is the root.  It doesn’t.  Simply use html {} instead
:last-child Χ ignores
:only-child Χ ignores
:nth-child() Χ These 7 selectors are all currently ignored by IE7 and all other grade-A browsers. Since there is no support for them, I can not compare IE7’s handling versus other browsers, and these selectors are useless for “targeting” other browser.
:nth-last-child() Χ
:first-of-type Χ
:last-of-type Χ
:only-of-type Χ
:nth-of-type() Χ
:nth-last-of-type() Χ
:empty Χ Ignored, but partially supported by FF and Netscape, so may be useful for targeting those browsers.
:not() Χ ignores
:target Χ ignores
:enabled Χ ignores
:disabled Χ ignores
:checked Χ ignores

Notes:

  • These tests were run in XHTML 1.0 Strict
  • I will elaborate here on the last 7 selectors when i have a bit more time
  • IE7 quirks in rendering CSS (versus understanding CSS) will be posted in a separate entry.
  • This article goes over IE7 failings. Please see CSS3 Selectors and Browser Support for other browser’s support of CSS3 selectors.
 
 

Double colon notation: :before versus ::before

Filed under: CSS (including hacks), Web Development — Estelle Weyl @ 11:15 pm

Understanding double-colon notation:

The double colon replaced the single-colon selectors for pseudo-elements in CSS3 to make an explicit distinction between pseudo-classes and pseudo-elements. For backward compatibility, the single-colon syntax is acceptable for pre-CSS3 selectors. So, :after is a pseudo-class and ::after is a pseudo-element.

This :: notation (double colon notation) was introduced by the W3 in order to “establish a discrimination between pseudo-classes and pseudo-elements. For compatibility with existing style sheets, user agents must also accept the previous one-colon notation for pseudo-elements introduced in CSS levels 1 and 2 (namely, :first-line, :first-letter, :before and :after). This compatibility is not allowed for the new pseudo-elements introduced in CSS level 3.” For more information, visit W3.

Browser Support for double-colon notation

Browsers that understand it:

  • Firefox 1.5
  • Firefox 2.0.X (Mac and Windows)
  • Opera (Mac and Windows)
  • Safari

Browsers that say WTF:

  • IE8 (Windows)
  • IE7 (Windows)
  • IE6 (Windows)
  • Netscape 7.1 (Mac)

See my other post CSS Selectors and Browser Support.

Note: Updated 3.19.09

 
 

CSS issues and hacks for Mac IE 5

Filed under: CSS (including hacks), Web Development — Estelle Weyl @ 3:19 pm

To Target Mac IE 5 only to the exclusion of all other browsers:

@media hack

/*\*//*/
@import "externalstylesheet.css"
/**/

Mac modified Tan Hack

* > html .someclass {proper\ty: value;}

To Exclude Mac IE only

Mac Band Pass Filter

@media all {
     #someDiv {property: value;}
}

Single declaration commented backslash hack

 /* start comment and include one \ so mac ignores just the next line */
     .ignoredByMac {property: value;}

Multiple Line commented backslash hack

/* put the backslach at the end of this line \*/
		.ignoredByMacIE {property: value;}
		#alsoIgnoredByMac {property:value;}
/* normal comment ends exclusion */

Issues in Mac IE 5 that will require above type hacks:

  • scrollbars appearing in absolutely positioned elements when the element is close to edge of browser window.
  • z-index issues when images have alignment. Shouldn’t be an issues since you shouldn’t be using the align attribute anymore. Float the image with CSS instead
  • text in floated elements with no width declared wrap incorrectly
  • background images don’t work correctly if inline style is declared with single quotes. Shouldn’t be an issue since you shouldn’t be using in-line styles.
  • radio and checkbox form elements inherit the background image of their siblings.
    declaring vertical-align with a background: inherit on the same element can crash the browser.


Why do we even care about such an old browser and Mac IE 5 that even Microsoft no longer supports?

Microsoft stopped supporting the standalone version if Mac IE, however, it was the default browser on the mac from 1997 to 2002, and was available on Macs until January 2006. When it was originally released, it was seen as a pretty good browser with decent CSS support. Mac OS users only account for 3.89% of site visits 1 and 1.7% of the site visits are on Safari, 2 so 2.19% of the population is on a mac and surfing the web with something other than Safari.  In otherwords, I can’t find the stats now on IE5 mac usage, but it is likely a large chunk of the 2.19% of the population that is using a mac, but not using safari.

Other IE 5 Mac Hints

  • In developing for Mac, it will cache your CSS. Simply open your CSS in another browser window and refresh it with every test.
  • Mac IE 5 chockes on the XML declaration. <?xml version="1.0" encoding="LATIN-1" standalone="yes" ?>  is optional and crashes IE5 on the Mac, so omit it.
  • You want it? You can download IE for the Mac here.
  • In the modified Tan Hack, make sure the slash is not in-front of A-F, as combinations such as \d are seen as hexidecimal numbers.