CSS, JavaScript and XHTML Explained

Quirks, random thoughts and funky finds discovered in day-to-day coding.

 

JavaScript Date Object July 29, 2007

Filed under: JavaScript, PHP, Web Development — Estelle @ 11:18 am

Javascript: Things you should know

Note: This is part IV of a "Javascript: Things you should know" series. I assume readers have an understanding of the core language. This section goes over the creation of date objects. Most resources go over creating a current time date object. This goes over the rest. The previous entry was JavaScript Objects. The next entry list all the date object methods. Please let me know what you think and it there is anything I am missing. Enjoy.

Creating JavaScript Date Objects:

There are fours ways of instantiating a date object:

  1. Without parameters
    Returns the users current date based on client computer’s clock.

    new Date();

    Example:
    var currentTime = new Date();

  2. With a numeric parameter:
    Returns the date measured from midnight January 1, 1970 (+/- GMT diff) plus the time in milliseconds that was passed as the parameter

    new Date(milliseconds);

    Examples:
    var startTime = new Date(0); // Returns
    your time when GMT hit the new year.
    var millenium = new Date ((365*30 + 7)*24*60*60*1000); // returns the millenium at GMT, The +7 is for the leap days.

  3. With a string parameter:
    The string parameter must be a date correctly formatted in string format. The Date object only seems to accept 1 date string format, which is provided in the examples below. The flexibility is only in the day: the number may include a leading zero, but it is not required.

    new Date(dateString)

    Examples:
    var auntsBirthday = new Date("September 4, 1902") // She’s 105
    var modifiedTime = new Date("July 27, 2005 12:22:00") // format must be exact

  4. With an array of parameters:
    Pass the different date element parameters in the order above. If you don’t specify all the parameters, or a parameter is non-numeric, 0 is passed. If your value is numeric, but not a valid value (such as hours == 25) no error will be thrown, though it may be a logic error. The most common error is the month parameter: remember that the arrays start at index of 0, so January is 0 and December is 11.

    new Date(year, month, day, hours, minutes, seconds, milliseconds)

    var modifiedTime = new Date(2007,7,27)
    var modifiedTime = new Date(2007,7,27,13,22,0)

Here are a few examples and what gets returned (javascript must be enabled):

  • currentTime = new Date()
  • timeBasis = new Date(0)
  • lastYear= new Date(-365*24*60*60*1000)

  • var currentTime = new Date("November 4, 2008");

  • anniversary = new Date(2003,8,21)
  • exactTime = new Date(1969,0,3,16,4,12,500)

Note:

  • new Date(0) will not return midnight of January first unless your computer set to GMT.

Common JavaScript Date Object Errors

  • new date()
    //Error: Date is case sensitive
  • new Date("412")
    //
    Error: No data conversion
  • new Date("June 31, 2005 29:95:73 ")
    //Logic Error: Too many hours in your day, and there are only 30 days in June.
    Returns July 2, 2005; which is unlikely your intention.
  • new Date("July 27, 2005 12:22pm")
    // invalid date error - doesn’t understand PM
  • new Date("2007-7-27")
    //Invalid Date: - string in wrong format**
  • new Date(1969,12,3,16,4)
    //Returns January 3, 1970 instead of December 3, 1969. Logic Error: monthArray is 0 - 11.

Notes:

  • When passing the month as a number, remember that the array starts at 0. Optional values are 0-11. Javascript will not throw an error, but there will be a logic error.
  • The date string must be of the correct fomat. The minimum is "Month dd, yyyy", to "Month dd, yyyy hh:mm:ss". The Month doesn’t seem to be case sensitive in my tests, but I haven’t checked all browsers. Good coding practices dictate that it should be capitalized. .
  • JavaScript uses the date of midnight, January 1, 1970 UTC as a starting point for all of its calculations.

An Example of Converting a PHP/Unix date to a usable JavaScript date:

So my quandry was that the date I received was written in an unusable format: The date the server sent was similar to 2007-07-22T22:57:35Z - yyyy-mm-ddThh:mm:ssZ, which is the date in ISO 8601 format (see converting ISO 8601 dates in PHP for a completely different take on conversion). I had to convert an ISO 8601 date to a parameter I could use in the Date object constructor

My first thought was to replace the T and Z with spaces, 2007-07-22 22:57:35 , which looks correct, but isn’t.
As we learned above (see Date error example above), date strings much be in the "Month dd, yyyy" format. The yyyy-mm-dd format will not work.

var myStringDate = "2007-07-22T22:57:35Z";
var myStringDate = new Date(myStringDate.replace(/\D/g, " ")) //returns "invalid date".

My second thought was to split the string into parameters.

var myStringDate = "2007-07-22T22:57:35Z";
var myStringDate = myStringDate.replace(/\D/g, " ");
var dObj = myStringDate.split(" ");
          //array is (2007, 07, 22, 22, 57, 35)
var myDate = new Date(dObj[0], dObj[1], dObj[2],
           dObj[3], dObj[4], dObj[5]);

That works, but gives me the wrong date. We have a logic error. The month array starts at 0. month[07] is August, not July. The solution was to subtract 1 from the 2nd parameter

var myStringDate = "2007-07-22T22:57:35Z";
var myStringDate = myStringDate.replace(/\D/g, " ");
var dObj = myStringDate.split(" ");
var myDate = new Date(dObj[0], (dObj[1]-1), dObj[2], dObj[3], dObj[4], dObj[5]);
document.write("Making a date from a string: " + myDate);



Writing Pretty Dates

Javascript 1.2 gave us some prettier ways of writing out dates. Still, you might not find the format you need with the methods provided. Here are some arrays that you should feel free to cut and paste into your code.

dyOfWeek = new Array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
daysOfWeek = new Array("Sunday", "Monday", "Tuesday", "Wednesday",
             "Thursday", "Friday", "Saturday");
monOfYear = new Array("Jan.", "Feb.", "Mar.", "Apr.", "May", "Jun.",
             "Jul.", "Aug.", "Sep.", "Oct.", "Nov.", "Dec.");
monthsOfYear = new Array("January", "February", "March", "April", "May",
    "June", "July", "August", "September", "October", "November", "December"); 

toLocaleDateString() works for much of what I need. But, sometimes you need something a little different. You can either edit using regular expressions, or you can create a pretty date from scratch.

Here are some formats and how to create them. I will use the date we created, the methods described above and the 4 arrays posted here.

(myTime.getMonth() + 1) + "/" + myTime.getDate() + "/" + myTime.getFullYear()
var hours =  myTime.getHours();
var ampm = (hours > 11)? "PM" : "AM";
hours = hours%12;
hours = (hours == 0)? 12 : hours;
time = hours + ":" + myTime.getMinutes() + " " + ampm;
July 2007
monthsOfYear[myTime.getMonth()] + " " + myTime.getFullYear()

Formatting Javascript Dates:

Want to extend the Date object to be nicely formated? Gavin Kistner did the work for us. Extending the Date Object which creates the a custormFormat for the date object. To use this prototype, include the function in your javascript, and call it this way:

var prettyDate = myDate.customFormat('#DDDD#, #MMM# #D#, #YYYY#');
var prettyTime = myDate.customFormat('#h#:#mm##ampm#');

Here’s the code:

Date.prototype.customFormat=function(formatString){ 
    var YYYY,YY,MMMM,MMM,MM,M,DDDD,DDD,DD,D,hhh,hh,h,mm,m,ss,s,ampm,dMod,th;
    YY = ((YYYY=this.getFullYear())+"").substr(2,2);
    MM = (M=this.getMonth()+1)<10?('0'+M):M;
    MMM = (MMMM=["January","February","March","April","May","June","July","August","September","October","November","December"][M-1]).substr(0,3);
    DD = (D=this.getDate())<10?('0'+D):D;
    DDD = (DDDD=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][this.getDay()]).substr(0,3);
    th=(D>=10&&D<=20)?'th':((dMod=D%10)==1)?'st':(dMod==2)?'nd':(dMod==3)?'rd':'th';
    formatString = formatString.replace("#YYYY#",YYYY).replace("#YY#",YY).replace("#MMMM#",MMMM).replace("#MMM#",MMM).replace("#MM#",MM).replace("#M#",M).replace("#DDDD#",DDDD).replace("#DDD#",DDD).replace("#DD#",DD).replace("#D#",D).replace("#th#",th);
     h=(hhh=this.getHours());
    if (h==0) h=24;
    if (h>12) h-=12;
    hh = h<10?('0'+h):h;
    ampm=hhh<12?'am':'pm';
    mm=(m=this.getMinutes())<10?('0'+m):m;
    ss=(s=this.getSeconds())<10?('0'+s):s;
    return formatString.replace("#hhh#",hhh).replace("#hh#",hh).replace("#h#",h).replace("#mm#",mm).replace("#m#",m).replace("#ss#",ss).replace("#s#",s).replace("#ampm#",ampm);
	 } 
 
 

Website Optimization: YSlow Tutorial July 26, 2007

Filed under: Best Practices, Web Development, firebug — Estelle @ 6:09 pm

Introduction to YSlow: optimizing your actual and perceived download speed

Two days ago Yahoo! officially released their Firebug extionsion "YSlow". YSlow is a tool that coherently presents factors effecting actual and perceived download speed. Many of the features available thru YSlow are avaible thru the Firebug NET tab, and digging thru other Firebug panes. What makes YSlow such an effective tool is that it displays those features in a understandable and actionable way.

Installing Yahoo! YSlow

YSlow is a page analysis tool that helps you optimize your web pages for better perceived and actualy download speed. YSlow is an extension to Firebug which is a FireFox plug-in (Yes, it’s an extension to an extension). You must download and install Firebug: If you need instructions, I wrote a introduction to Firebug tutorial last month.

To install YSlow, download YSlow from the Mozilla website. Click on the "Install Now" button, then on "Install". You will need to restart Firefox for both the YSlow and the Firebug add-ons to work, so you might as well download and install both before restarting FireFox.

Turning YSlow on

While the YSlow icon will always be present in the right of the status bar, it is not actively running and analying all your page visits all of the time. To get YSlow to always be active, righ click on the word YSlow in the status and choose "Autorun" from the popup menu.

AutoRun: Having YSlow on all the time

You likely don’t want YSlow running all the time. The benefit of having YSlow on autorun is that you:

  1. Total download weight and time (to the right of the YSlow icon in the status bar),
  2. Faster access to YSlow features.

The downside is that having YSlow on all the time

  1. Faster perceived download time
  2. Uses RAM

My recommendation is to only have it on autorun if you are actively working on optimizing; and then turn it off the rest of the time.

Turning YSlow on Selectively

Unless you have selected autorun, you have to activate YSlow by opening up Firebug and clicking on the YSlow Tab, which brings you to a page instructing you how to activate YSlow by selecting which type of analysis you’re interested in. Select Performance, Stats or Component. Selecting from the Tools or Help menu will not analyze your page. For example, if you select JSLine from the Tools menu, you get results for the most recently analyzed page. The Tools drop down menu may actually be greyed out to start.

YSlow Screen Shot.

Using YSlow

YSlow Performance

YSlow gives you a grades for each of 13 areas of download speed plus an over grade with total score. You get graded on the number of HTTP requests made, using expires headers, gzipping files, having CSS at the top, javascript at the bottom, not using CSS expressions, minimizing the number of domains hit for page componenents, minifying javascripts, avoiding redirects, removing duplicate javascript functions, turning off eTags and having static files served from Content Distribution Networks (CDN). I will go over most of these in my blog post on improving perceived and actual download speed. Not included in the list is reducing the number of HTTP requests even further for a home page only by using inpage CSS and JavaScript.

More information: If you don’t get an A on any of the parameters, simply click on the arrow to the right of the parameter, and more information will appear. You can also click on the "expand all" link in the upper right which will expand the sections not earning an A with an explanation of what the failings were. No matter your grade, if you click on the name of the parameter, you will be redirected to the Yahoo Developer Network for details on what the parameter means and how it effects your perceived and/or actual download speed.

Changing Grades: If you don’t like the grading system, you can configure YSlow to weight things differently by altering the javascript file. Search for yslow.js on your computer. Mine was located at c:\documents and settings\estelle\Application Data\Mozilla\Firefox\Profiles\extensions\yslow@yahoo-inc.com\default\preferences\.

YSlow Stats Tab

The Stats tab lets gives provides you with 3 bits of information:

  • Page downloads when Cache is empty
    This includes the number of HTTP requests and file weight of all the HTML, JavaScript, CSS files and images, includeing images called from the CSS, downloaded to render the page. A few things to note about this value: if your page is set as the home page for someone, IE pretends the cache is empty and downloads everything, irrespective of expires headers. If you click on the "(est)" next to a cache parameter, YSlow provides you with an estimate as to how your speed can improve.
  • Page downloads when Cache is full
    This includes only the number of HTTP requests and file weight for the files that do not have a future expires date and are not cached. The total includes thell the HTML, JavaScript, CSS files and images not cached.
  • Cookies

YSlow Components Tab

The Components tab describes in more detail each of the files that make up the sum total in "Page downloads when Cache is empty" described above. For each HTML (or PHP, or whatever the main file is), CSS, JavaScript, CSS image, regular image, etc., YSlow grabs the header information and provides the following in human readable form:

  • File Type
  • File URL
  • Expires header date, if any, or today’s date if not explicitly set
  • Gzip status
  • Server response time
  • Un-g-zipped file size
  • E-Tag

If you want more information, clicking on the magnifying glass next to the URL displays the headers (this is also available thru Firebug’s NET tab). If you click on the actual URL, it will open up that URL — be it an HTML file, a CSS file, an Image — in a new browser window.

YSlow Tools Tab

The Tools tab provides "links" to 4 reports: JSLint, JS, CSS, Printable Version

  • JSLint:
    I am not 100% sure, but I think JSLint explains errors that would need to be rectified before passing your JavaScript file thru Crockford’s JSLint minification tool. For JSLint to work, you have to include components in your Javascript that would otherwise be optional in the loosely typed language, such as ending your lines with a semi-colon. The JSLint response warns you of these necessary edits..
  • JS:
    Prints to the browser all the JavaScript that is included in the currently analyzed page
  • CSS:
    Prints to the browser all the CSS that is included in the currently analyzed page. This is similar to the Firefox Developer Toolbar. I prefer the toolbar version since it has the functionality of allowing you to close out individual CSS sources.
  • Printable Version:
    While this may seem like just a printable version of the performance tab, this page is actually very useful. It delineates all the things you can do to score a 100% on the Performance section of YSlow. It basically explains the performance tab in detail — what you would see if you clicked on the "expand all" link in the performance tab.

Missing Features

Dynamic Downloads not captured:
YSlow isn’t perfect. It does not display properties of elements brought into the page dynamically such as multimedia, javascript rendered images, componenents rendered from XMLHTTPRequests, or any DOM changes. You can use Firebug’s NET tab to garner that data. It seems that YSlow takes a look at the page being analyzed, and does an XMLHTTPRequest to get download time information. Firebug, on the other hand, collects and stores the information for each request. For true web page weight, Firebug is more precise. For actual download time, Firebug is also more precise. For perceived download time, however, YSlow gives you a good estimate.

 
 

XHTML Deprecated Elements and Attributes July 24, 2007

Filed under: Web Development — Estelle @ 10:31 am

If you’re coding with a strict doctype, you definitely don’t want to use any deprecated attributes or elements. So, what are those deprecated elements and attributes that you shouldn’t use? See below:

Deprecated Elements

Name Description Alternative
applet Java applet  
basefont base font size font-size: 100%;
center shorthand for DIV align=center text-align: center;
dir directory list  
font local change to font font-family: arial; font-size: 0.8em;
isindex single line prompt  
menu menu list  
s strike-through text style text-decoration: line-through;
strike strike-through text text-decoration: line-through;
u underlined text style text-decoration: underline;

 

Deprecated Attributes

Attribute Deprecated in these elements CSS (or HTML) Alternative
align caption, img, input, object, legend, table, hr, div, h1, h2, h3, h4, h5, h6, p CSS attribute: text-align
alink, link, vlink body CSS selectors: a, a:link, a:visited, a:hover, a:active, a:visited:hover
CSS attribute: color:
background body CSS attribute: background-image:
bgcolor table, tr, td, th, body CSS attribute: background-color: or background:
border img, object CSS attribute: border:
clear br CSS attribute: clear: left | right | both | none
compact dl, ol, ul CSS attribute: line-height, min-height or height: with overflow: set.
height td, th CSS attribute: line-height for cell content; don’t use tables for layout
hspace img, object CSS attribute: padding
language script HTML attribute: type
HTML attribute value:
MIME type, ex. type="text/javascript"
name img, a, applet, form, frame, iframe, map HTML attribute: id
noshade hr  
nowrap td, th CSS attribute: white-space:
size hr CSS attribute: width: or margin:
start ol Anyone know? Please tell me.
target a Anyone know? Please tell me.
text body CSS attribute: color
type li, ol, ul CSS attribute: list-style-type
value li Anyone know? Please tell me.
version html HTML Markup: use a DTD
vspace img, object CSS attribute: padding: or margin:
width hr, td, th, pre CSS attribute: width: