Wednesday, November 12, 2008

Does your website disappear in IE8?

Mine did.

I was recently given a pretty large redesign project, and during the planning stages I took the opportunity to add a long-missing DOCTYPE to the site. I chose a nice HTML 4.01 Transitional flavor because there was no way in hell the site was going to resemble anything close to XHTML anytime soon. At the very least, it would 1) get the site out of quirks mode, and 2) give us an eventual path to validation.

(I'm including this info to illustrate: we had a proper DOCTYPE, and knew the site would not be valid HTML going in.)

Months after the project was complete and launched, word came down that the site was missing in IE8. Not broken. MISSING. Like, "the page is blank."

No partial loading, no sudden flicker, no error message. The site simply would not render.

I was considering hard liquor as my preferred solution when one of my co-workers mentioned something he'd heard about a new META element, something about versioning. Ah, yes, that version targeting thing.

I added the following to the global website header:

<meta http-equiv="X-UA-Compatible" content="IE=7" />

...and suddenly the site worked in IE8.

This is not a "solution." I still don't know why the site vanishes in IE8. I mean, it rendered perfectly fine in IE5, IE5.5, IE6 and IE7 so OF COURSE IT MAKES TOTAL SENSE THAT IT COMPLETELY VANISHES IN IE8. Right?

No. It does not make sense. Anyway, when I do discover the root cause, I'll post it here. In the meantime, I guess I'll be asking IE8 to dumb it down to my level.

Thursday, July 17, 2008

Missing form ACTIONs

Say you want to disable a submit button when it's clicked, to prevent the user from submitting twice:

<form name="myform">
  <input type="submit" value="Submit" onclick="this.disabled = 'true';">        
</form>

On Windows, this works fine in IE but not in Firefox. Or so it appears. What's going on?

Oops, you forgot an ACTION attribute in your form. (It's okay, this is common if you're planning an Ajax-style app.) Without it, IE just ignores the submit click, but Firefox uses the current page as the default action. So it effectively reloads the page, resetting the button state.

The thing is, the submit button is being disabled in FF, just like in IE, but depending on how fast the page reloads, you might not even notice.

Wednesday, July 16, 2008

Function reference vs. function call

Here's a JavaScript function definition:
function foo() {
  alert('foo!');
}
You can refer to that function like this:
foo
And here is how to call (execute) the function:
foo()
Even experienced developers new to JS tend to get these confused. For example, jQuery's getJSON method allows you to specify a function to be executed once the operation is complete. Be careful not to plug in the function call when what you really need is a function reference:
$.getJSON( "action.php", {data:'some data here'}, foo() );
This will execute the foo function instantly. Not what you want. So leave off the parens:
$.getJSON( "action.php", {data:'some data here'}, foo );
This merely passes a reference to the function. It won't execute until it's called by jQuery.

Wednesday, April 16, 2008

A good enough addEvent

O HAI, this blog is nearly dead these days. But before it truly shuffles off into the sunset, allow me to point you to filosofo's "good enough" addEvent. Austin gets around PPK's pesky requirements by ignoring one of them (namely, having a corresponding removeEvent).

I love this solution because it mirrors much of my recent experiences with JavaScript. Honestly, I can't remember the last time I needed anything more than some variation of toggle() and I can count on one hand the number of times I've need to detach an event since 1998.

Kudos to Austin for thinking differently.

Sunday, July 01, 2007

Some reader contributions to Calendar tutorial

When I started SZOJ I promised myself I wouldn't abruptly shut down the blog if I lost interest; I'd just go radio silent until my interest was piqued again. That said, it's been a long while. So here are two things:

Rory Parle wrote in to point out you can use Math.ceil to determine the number of rows you'd need to safely render a calendar:

Math.ceil((monthLength + startingDay) / 7);

Michiel van der Blonk suggested a way to determine the number of days in a month:

var d = new Date(nYear, nMonth + 1, 0); // nMonth is 0 thru 11
return(d.getDate());

The mechanism here is the Date constructor will attempt to convert year, month and day values to the nearest valid date. So in the above code, nMonth is incremented to find the following month, and then a Date object is created with zero days. Since this is an invalid date, the Date object defaults to the last valid day of the previous month — which is the month we're interested in to begin with. Then getDate() returns the day (1-31) of that date — voilá, we have the number of days.

Bonus: it also seems to automatically correct for leap year. It feels like a hack but it seems to work consistently.

Thanks to Rory and Michiel for their contributions.

Monday, March 19, 2007

How to build a simple calendar with JavaScript

While there are lots of JavaScript-based calendar widgets out there, there's not much in the way of explaining how they work for the JS acolyte. I recently had the opportunity of building one from memory (and best of all, for no particular reason), using none of the popular JS libraries. This is the tutorial I wish I had found five years ago.

This series of posts will cover:

  1. how to create a simple calendar view with JavaScript
  2. how to tie the calendar to an HTML element for rendering
  3. how to add next/previous month controls
  4. how to add date picker functionality

Part One: a basic calendar display

We're ready to start laying the groundwork for our calendar widget. Here are the steps we'll be taking:

  1. define some global variables to hold common values
  2. define the calendar object and its arguments
  3. write a method to generate the HTML needed to render the calendar
  4. write a method to return the HTML

The Date object

I used to fear the JavaScript Date object, but it's actually fairly simple. In short, here's what it does:

  1. parses a given date, and provides useful information about that date
  2. if no date is specified, the current date is used as the default

A full discussion of the Date object is beyond the scope of this tutorial. You can find documentation here. However, for the purposes of this project, it's important to understand what the Date object doesn't do:

  • it doesn't know the names of months or days of the week
  • it doesn't know how many days are in a given month
  • it doesn't compensate for leap year
  • it doesn't know the day of the week on which a given month begins

Surprisingly, the Date object isn't used in this widget as much as you'd expect. It's primarily used to determine the current date (if needed) and the starting day of the week for the specified month.

Global variables

As stated above, the Date object doesn't provide us with everything we need, so we have to compensate with a few predefined arrays of values.


// these are labels for the days of the week
cal_days_labels = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];

// these are human-readable month name labels, in order
cal_months_labels = ['January', 'February', 'March', 'April',
                     'May', 'June', 'July', 'August', 'September',
                     'October', 'November', 'December'];

// these are the days of the week for each month, in order
cal_days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
These are intentionally defined in the global scope, as they may be shared with multiple calendar widgets. The naming convention is arbitrary; you may prefer to append them to the calendar constructor to prevent collisions with other variables. Since the Date object returns integers for month (0-11) and day (1-31), we'll be able to use those as indexes for looking up the human-readable labels, as well as the number of days in the specified month.

But wait, how do we compensate for leap year when February is hard-coded at 28 days? Don't worry, it's coming later in this tutorial.

In addition, we'll need a Date object representing the current date, as a fallback:
// this is the current date
cal_current_date = new Date(); 

The Calendar constructor

Our constructor is pretty basic at the moment. I've designed it to take two arguments, a month and year (both integers) which will represent the intial calendar state. If these arguments are missing or null, the global default date object will be used instead.
function Calendar(month, year) {
  this.month = (isNaN(month) || month == null) ? cal_current_date.getMonth() : month;
  this.year  = (isNaN(year) || year == null) ? cal_current_date.getFullYear() : year;
  this.html = '';
}

Right now you might be saying "hey, why the long syntax? Can't we just do a shortcut like this?"

this.month = month || cal_current_date.getMonth();

One of the pitfalls of this method is that zero can be interpreted as false, which means if we specify zero (January) for our month, this expression would use the default month instead.

We also want the option to pass null for one or both of the values. The isNaN() function returns true when passed a null value, which will produce an incorrect result. So we have to test for both conditions: the argument must either be not a number or null for the default to be used.

HTML generation

Here's where we take the date info and stitch together an HTML calendar grid view. Let's start with an empty method definition:

Calendar.prototype.generateHTML = function(){

}

Not familiar with object prototyping in JavaScript? Here's some good reading.

Now let's step through everything this method has to handle.

First day of the week

March 2007 begins on a Thursday, but the Date object doesn't know that. However, if we specifically give it the date of "March 1 2007" to parse, it can tell us that day of the week as an integer (from 0-6). So, let's feed it such a date:

var firstDay = new Date(this.year, this.month, 1);

We can now query the new Date object for the day of the week:

var startingDay = firstDay.getDay();
// returns 4 (Thursday)

So now the widget knows that March 2007 starts on the 5th day of the first week (remember, we're counting from zero like computers do).

Number of days in the month

This one's easy. Just use the numeric month value to look up the value in our days-in-month array:

var monthLength = cal_days_in_month[this.month];

Compensate for leap year

Right, how does the widget know if it's leap year or not? This stumped me until I did a Google code search and found a widely-implemented approach that uses the modulus operator:

if (this.month == 1) { // February only!
  if ((this.year % 4 == 0 && this.year % 100 != 0) || this.year % 400 == 0){
    monthLength = 29;
  }
}

Damn, I'm glad I didn't have to figure that out. Thanks, Google Code!

Constructing the HTML

We're ready to start building the HTML string for our calendar view. First, the header stuff:

var monthName = cal_months_labels[this.month];
var html = '<table class="calendar-table">';
html += '<tr><th colspan="7">';
html +=  monthName + "&nbsp;" + this.year;
html += '</th></tr>';
html += '<tr class="calendar-header">';
for (var i = 0; i <= 6; i++ ){
  html += '<td class="calendar-header-day">';
  html += cal_days_labels[i];
  html += '</td>';
}
html += '</tr><tr>';

It's pretty straightforward: we begin with a table and header containing the month and year. Then we use a for loop to iterate over our human-readable days-of-the-week array and create the first row of column headers.

There are more efficient ways of concatenating HTML, but I thought this was the most clear. And don't gimme no lip about using a TABLE vs. a bunch of floated DIVs — I may be a standardista but I'm not a masochist.

Now for the tricky part, the remaining boxes. We need to make sure that we don't start filling in boxes until we've reached the first weekday of the month, and then stop filling them in when we've reached the maximum number of days for that month.

Since we don't know how many rows we'll need, we'll just generate a safe number of rows — like ten or so — and break out of the loop once we've run out of days. Here we go:

var day = 1;
// this loop is for is weeks (rows)
for (var i = 0; i < 9; j++) {
  // this loop is for weekdays (cells)
  for (var j = 0; j <= 6; j++) { 
    html += '<td class="calendar-day">';
    if (day <= monthLength && (i > 0 || j >= startingDay)) {
      html += day;
      day++;
    }
    html += '</td>';
  }
  // stop making rows if we've run out of days
  if (day > monthLength) {
    break;
  } else {
    html += '</tr><tr>';
  }
}

html += '</tr></table>';

this.html = html;

The real brain-twister is here:

if (day <= monthLength && (i > 0 || j >= startingDay)) {

...which roughly translates to "fill the cell only if we haven't run out of days, and we're sure we're not in the first row, or this day is after the starting day for this month." Whew!

Here's the complete code for our HTML-generating method:

Calendar.prototype.generateHTML = function(){

  // get first day of month
  var firstDay = new Date(this.year, this.month, 1);
  var startingDay = firstDay.getDay();
  
  // find number of days in month
  var monthLength = cal_days_in_month[this.month];
  
  // compensate for leap year
  if (this.month == 1) { // February only!
    if((this.year % 4 == 0 && this.year % 100 != 0) || this.year % 400 == 0){
      monthLength = 29;
    }
  }
  
  // do the header
  var monthName = cal_months_labels[this.month]
  var html = '<table class="calendar-table">';
  html += '<tr><th colspan="7">';
  html +=  monthName + "&nbsp;" + this.year;
  html += '</th></tr>';
  html += '<tr class="calendar-header">';
  for(var i = 0; i <= 6; i++ ){
    html += '<td class="calendar-header-day">';
    html += cal_days_labels[i];
    html += '</td>';
  }
  html += '</tr><tr>';

  // fill in the days
  var day = 1;
  // this loop is for is weeks (rows)
  for (var i = 0; i < 9; i++) {
    // this loop is for weekdays (cells)
    for (var j = 0; j <= 6; j++) { 
      html += '<td class="calendar-day">';
      if (day <= monthLength && (i > 0 || j >= startingDay)) {
        html += day;
        day++;
      }
      html += '</td>';
    }
    // stop making rows if we've run out of days
    if (day > monthLength) {
      break;
    } else {
      html += '</tr><tr>';
    }
  }
  html += '</tr></table>';

  this.html = html;
}

Returning the HTML

By design, the generateHTML method doesn't return the finished HTML string. Instead, it stores it in a property of the calendar object. Let's write a getter method to access that string.

Calendar.prototype.getHTML = function() {
  return this.html;
}

Okay, let's see what we've got!

Using the calendar

The widget may be complex on the inside, but it's ridiculously easy to implement. Here's how to embed a calendar displaying the current month into a web page:

<script type="text/javascript">
  var cal = new Calendar();
  cal.generateHTML();
  document.write(cal.getHTML());
</script>

Now let's set it to September 2009:

<script type="text/javascript">
  var cal = new Calendar(8,2009);
  cal.generateHTML();
  document.write(cal.getHTML());
</script>

The Demo!

Here's our calendar widget in action.

That's nice, but...

We're stuck displaying only one month?

Shouldn't generateHTML and getHTML be called automatically?

And WTF is up with that lame document.write?

Yep, this simple calendar is "simple" alright. Later this week we'll look at a much slicker way to integrate the calendar into webpages and add controls to transform our humble static calendar view into a full-blown datepicker.

Wednesday, March 07, 2007

The Mark Of The n00b

When I'm debugging or otherwise vetting someone's JavaScript work, I tend to look for evidence that indicates:

  1. the author is new to JavaScript, and/or
  2. the author cut-and-pasted this code

Neither of these are showstoppers, especially if the result is a neat-o web application or widget. But it does tend to drive me a little nuts sometimes.

Case in point: using "javascript:" in HREFs, a pet peeve of mine. It's not technically incorrect and it "just works" almost all modern browsers. It's just "wrong," in the same way that using <b> instead of <strong> is "wrong" and using TABLEs for layout is "wrong."

It's wrong from a craft point of view. It's the JavaScript equivalent of "eh, let's just shove the table markup into the database along with the content."

(Worse yet is "JavaScript:" (camel-cased) or something like "onclick='JavaScript:...'" I don't know of a single browser that falls over when the latter is used, but when someone sends me broken code to debug that has "JavaScript:" in the event handlers, the first thing I wonder is, "hm, what else is being overlooked here?")

Thing is, I don't expect JS newbies to know this stuff* because other than some tongue-clucking from old JS cranks like myself, there aren't any hard consequences.

And you. Do you have any favorite "mark of the newbie" things that drive you insane?

* that's why I run this blog

Return false to prevent jumping scrollbars

I like what Harry Maugans is doing over at his site with his JavaScript how-tos. It's back-to-basics stuff, but judging from the number of Diggs he gets, people are interested in how this stuff works under the hood.

In his tutorial "How To Create A Collapsible DIV with JavaScript and CSS," Harry writes regarding the use of the HREF attribute in anchors that trigger JS actions:

Another common do-nothing insert to use for the href property is a pound sign (#), and while that will work, it'll also move the user’s scroll bar to the very top of your website, which can get quite annoying.

The way to get around the scrolling problem is to include a "return false;" in your event handler:

<a href="#" onmousedown="toggleDiv('mydiv'); return false;">
  Toggle Div Visibility
</a>

Again, basic stuff, easily overlooked.

(I wrote to Harry about this but I don't think he approved my comment. That's okay; it's why we have Trackback :)