An IE6-compatible solution for :hover

Something I like to incorporate on web sites with tables is automatic background highlighting of the row that the mouse is hovering over. This is easy to do with CSS:

table.hover tr:hover
{
background-color:#ffffcc;
}

All you need to do is give your table tag the hover class, and your mouseover hover background color works!

In all browsers except IE6, of course. IE6 only supports the :hover pseudo-class on anchor () tags. (There’s lots of other things that IE doesn’t support or supports wrong, but that’s a story for another day.)

How can we get IE6 to hover our table rows? By using a little JavaScript and the Prototype library. Our solution requires two steps:

  1. Write some code to automatically detect mouseover and mouseout events on table rows, applying and removing a CSS class to the rows as the events occur.
  2. Add the CSS class to our CSS file.

First we’ll add a tr.hover declaration to our CSS.

table.hover tr:hover, table.hover tr.hover
{
background-color:#ffffcc;
}

Notice that I kept the table.hover parent selector; this is important, as we’ll use that to ensure we only apply our hover code to table rows in tables that have the hover class.1

To get the class added (and removed) from our table rows, we use Prototype to find all elements that match the CSS selector table.hover tr, and for each one, hook a function to the onmouseover and onmouseout properties.

$$('table.hover tr').each( function(e) {
e.onmouseover += function() {
Element.addClassName(e, 'hover');
};
e.onmouseout += function() {
Element.removeClassName(e, 'hover');
}
});

Problem #1: The code above is applied to all browsers. We only need it applied to versions of IE prior to 6.0. A simple hack for this was found at Ajaxian, and is added below.

if (!window.XMLHttpRequest)
{
$$('table.hover tr').each( function(e) {
e.onmouseover += function()
{
Element.addClassName(e, 'hover');
};
e.onmouseout += function()
{
Element.removeClassName(e, 'hover');
}
});
}

Problem #2: What if our event model already declared an event on the onmouseover or onmouseout properties? The script above would clear any existing event handlers. The solution is to use Prototype’s Event.observe method to hook the functions.

if (!window.XMLHttpRequest)
{
$$('table.hover tr').each( function(e) {
Event.observe(e, 'mouseover', function() {
Element.addClassName(e, 'hover');
});
Event.observe(e, 'mouseout', function() {
Element.removeClassName(e, 'hover');
});
});
}

Problem #3: If the JavaScript runs before the page loads, it may not apply the event handlers to our table. This is also resolved by using Event.observe to run the above code only after the window loads.

if (!window.XMLHttpRequest)
{
Event.observe(window, 'load', function() {
$$('table.hover tr').each( function(e) {
Event.observe(e, 'mouseover', function() {
Element.addClassName(e, 'hover');
});
Event.observe(e, 'mouseout', function() {
Element.removeClassName(e, 'hover');
});
)};
)};
}

There you have it — a :hover hack for IE6 that doesn’t break IE7 or Firefox. It should work with all other modern browsers, though some old browsers may have issues with it. If you know of any browsers which break with this solution, let me know.


1 The use of the class name hover caused a problem when including YUI’s Button CSS code. In their CSS, they have a CSS selector for .yuibutton.hover. Apparently, IE6’s issue with these selectors caused my entire table to pick up the CSS from .yuibutton.hover. To fix this, I renamed YUI’s CSS selector to .yuibutton.yuihover and updated their JavaScript (just search/replace 'hover' with 'yuihover').

Customizing TableKit to stripe column groups

I’m a big fan of TableKit, a JavaScript library (based on Prototype) that provides client-side sorting, row striping, column resizing, and more. (Check out their demo to see more.) There’s one feature I needed on a recent project that was missing: the ability to stripe column groups (defined with the colgroup tag) with alternating background colors (as you would stripe rows of alternating colors). It was easy to add this functionality to TableKit by adding the following JavaScript code to the TableKit library.

TableKit.ColGroups = {
	stripe : function(table) {
		var colgroups = table.getElementsBySelector('colgroup');
		colgroups.each(function(cg,i) {
			TableKit.ColGroups.addStripeClass(table,cg,i);
		});
	},
	addStripeClass : function(t,cg,i) {
		t = t || cg.up('table');
		var op = TableKit.option('colgroupEvenClass colgroupOddClass', t.id);
		$(cg).removeClassName(op[0]).removeClassName(op[1]).addClassName(
			((i+1)%2 === 0 ? op[0] : op[1]));
	},
	hide : function(colgroup) {
		Element.setStyle(colgroup,{visibility:'collapse'});
	}
};

The code above expects two new TableKit options, named colgroupEvenClass and colgroupOddClass. To add those as available options to TableKit, find the section of code below and add the two lines named colgroupEvenClass and colgroupOddClass.

	...
	options : {
		autoLoad : true,
		stripe : true,
		sortable : true,
		resizable : true,
		editable : true,
		rowEvenClass : 'roweven',
		rowOddClass : 'rowodd',
		sortableSelector : ['table.sortable'],
		columnClass : 'sortcol',
		descendingClass : 'sortdesc',
		ascendingClass : 'sortasc',
		noSortClass : 'nosort',
		sortFirstAscendingClass : 'sortfirstasc',
		sortFirstDecendingClass : 'sortfirstdesc',
		resizableSelector : ['table.resizable'],
		minWidth : 10,
		showHandle : true,
		resizeOnHandleClass : 'resize-handle-active',
		editableSelector : ['table.editable'],
		formClassName : 'editable-cell-form',
		noEditClass : 'noedit',
		editAjaxURI : '/',
		editAjaxOptions : {},
		colgroupEvenClass : 'colgroupeven',
		colgroupOddClass : 'colgroupodd'
	},
	...

With that, you can now stripe your column groups by doing the following. The example below assumes a table whose id is mytable.

TableKit.ColGroups.stripe($('mytable'));

That command will apply two classes to your colgroup tags — by default, colgroupEven and colgroupOdd. Most modern browsers will pass down the background color for a colgroup to its table cells, "striping" your column groups.

IE7 reverses table rows during Insertion.After

I found yet another interesting bug in IE7, related to using Prototype‘s Insertion.After command to insert additional table rows into an existing table. Apparently, IE7 will reverse the order of the table rows being inserted. As a proof of concept, I’ve set up an ie7 table insert bug test page to prove my point.

Here’s how to duplicate this bug.

  1. Create a new web page (we’ll call it test.htm).
  2. Create a <table> and add a few rows.
  3. Give one row a specific id (such as id="insertAfterThis").
  4. Create a separate web page (call it testdata.htm) with more table rows — just the <tr>...</tr>, nothing else.
  5. Add the following JavaScript to run after the window loads:
    new Ajax.Request('testdata.htm', { method:'get', onSuccess:function(transport) { new Insertion.After('insertAfterThis', transport.responseText); } });
  6. Load the test.htm page in Firefox, and see how the rows are inserted in the order they exist in the testdata.htm file.
  7. Load the test.htm page in IE, and see how the order of the rows is reversed.

It’s quite a frustrating bug, because there’s apparently only two ways to work around it:

  1. Figure out a way to add markup that forces IE to add the rows correctly.
    OR
  2. Have IE receive the table rows from your Ajax call in reverse order (so it’ll reverse it again into the correct order).

Considering we’re not even sure if #1 is possible, it’s a very frustrating bug. Some may say it’s a bug with the Prototype library, but I doubt it, since Prototype is simply inserting text — it has no idea there’s a table involved. IE7 reveals yet another illogical bug.

Microsoft OKs community development of CSS Friendly Control Adapters

Back in late 2006, I modified Microsoft’s CSS Friendly ASP.Net 2.0 Control Adapters to be distributable as a single DLL. Since that time, the code I wrote was downloaded from this web site, and everything seemed good, at least until the server crashed. After being prodded by a few people in the ASP.Net community, I moved this little project over to CodePlex. Before doing so, I checked to make sure this was OK with Scott Guthrie, the grand poohbah of ASP.Net at Microsoft. (You’ve got to cover your basis!)

Anyway, today I read a post on the ASP.Net forums stating that Microsoft OKs community development of the CSS Friendly Control Adapters. In short, this is a good thing for the users of this product, for reasons that are explained in that thread, and it looks like I’ll be more involved with the ongoing development of these adapters in the future. It’s also nice to see your efforts noticed by the largest software development company in the world. 😉

I will keep the pages on this site that mentioned these adapters, but I highly suggest everyone who used them to bookmark the CodePlex project “CSSFriendly” and use that as their source of code and information going forward.

Simple rounded corners

A friend of mine was trying to get a rounded corner bar at the top of some web content. He already had the rounded corner images but didn’t know the HTML and CSS markup. I sent him over the following snippet of code as an example:

    <div style="width:100%;background-color:blue;height:14px;margin:0px;padding:0px;font-size:5%;">
        <div style="float:left;background-image:url('left.gif');width:14px;height:14px;">
        </div>
        <div style="float:right;background-image:url('right.gif');width:14px;height:14px;">
        </div>
    </div>

To understand, note the following:

  • The width:100% should be set the width appropriate to your content.
  • The width and height (14px in the example above) should be replaced by the actual width and height of your rounded corner images.
  • What’s with the font-size:5%? Making the font size very small will ensure that any white space will not create a block larger than the desired height (in our case, 14px).

The following bar was made using the above content, using images from this web site.

CSS Adapters for Membership Controls (working versions)

On September 6, the guys at Microsoft released the second beta version of their CSS Friendly ASP.Net 2.0 Control Adapters. In addition to bug fixes were CSS implementations of the membership controls – specifically, the Login, CreateUserWizard, PasswordRecovery, LoginStatus, and ChangePassword controls.

Unfortunately for the membership controls, it didn’t really work. This bothered me, because I’ve been using a hacked version of these controls that strips out TABLE-related tags for some time. The hacks work, but they’re hacks, and they have some quirky behavior.

I wrote a post on the ASP.Net forums, in which I described the problem.

I was glad to see that membership controls were added to the latest beta release. However, I did notice that all of them (with one exception) still put a TABLE wrapper around the content when using a templated control. It happens on the Login and PasswordRecovery controls…

Ironically, the CreateUserWizard did not add a table wrapper around the CreateUserWizardStep — but it did add it around the CompleteWizardStep.

Russ Helfand (obviously one of the guys working on the CSS adapters) responded and gave some tips. After some trial and error, we figured out some implementation updates that fix the problem for the Login, CreateUserWizard, and PasswordRecovery controls — an approach that can likely be used to fix other “broken” CSS adapters, too. A snippet of the solution follows.

Russ Helfand suggested:

Let’s look at the LoginAdapter as an example, http://www.asp.net/CSSAdapters/srcviewer.aspx?inspect=%2fCSSAdapters%2fMembership%2fLogin.aspx. In particular, I want you to look at line 125 where the template container is being rendered. I’m considering changing that from:

container.RenderControl(writer);

To:

foreach (Control c in container.Controls)
{
c.RenderControl(writer);
}

It would be helpful if you could try that fix out locally and let me know if it works well for you.

I tried it, and it worked!

I used a similar approach for other controls. Take the CreateUserWizard adapter as an example. Since this adapter only added the table in the Completed step, I made the following change in the RenderContents() method (around line 181):

        activeStep.RenderControl(writer);

… changes to:

        if (activeStep.StepType == WizardStepType.Complete)
            foreach (Control c in activeStep.Controls[0].Controls[0].Controls[0].Controls[0].Controls)
            {
                c.RenderControl(writer);
            }
            else
                activeStep.RenderControl(writer);

For the PasswordRecovery adapter, there’s three places to change — each instance of the RenderControl() method in the RenderContents() method should be commented out and replaced by the foreach loop.

    //passwordRecovery.UserNameTemplateContainer.RenderControl(writer);
    foreach (Control c in passwordRecovery.UserNameTemplateContainer.Controls)
        c.RenderControl(writer);

    ...

    //passwordRecovery.QuestionTemplateContainer.RenderControl(writer);
    foreach (Control c in passwordRecovery.QuestionTemplateContainer.Controls)
        c.RenderControl(writer);

    ...

    //passwordRecovery.SuccessTemplateContainer.RenderControl(writer);
    foreach (Control c in passwordRecovery.SuccessTemplateContainer.Controls)
        c.RenderControl(writer);

That’s some weird behavior, but it works, and it doesn’t seem to break any of the functionality. Be sure to check out the complete thread on the ASP.Net forums for details.

A wonderfully simple, wonderfully useful IE CSS hack

For the past few years, I’ve been doing a lot of web development. Part of my design mantra (at least from a code perspective) is table-less design using CSS that works in as many browsers as humanly possible.

Since Firefox‘s support for CSS standards is superior to that of IE, I generally code everything so it looks good in Firefox, then apply hacks to get it to work in IE. (Most other browsers require minimal tweaking once something works well in Firefox and IE.) At times, the hack is to add some IE-specific CSS code, which is usually done using the asterisk hack:

.myClass {
 background-color:white;
}
* html body .myclass {
 background-color:black;
}

Only IE recognizes the second line, so in IE, the background color of any element with the myClass class will be black; for all other browsers, it will be white.

However, this hack can be replaced by one I found today, which is beautifully simple and elegant: add an underscore before the CSS property name.

body {
 background: green; /* show to Mozilla/Safari/Opera */
 _background: red; /* show to IE */
}

It works in IE Windows only, according to the guy who wrote about it on his blog, Joen Asmussen. Hats off to you, Joen — a great solution not only in its simplicity (one extra character) and in its readability (you can visualize the IE-only hack in the same content as your non-IE CSS).

For more on CSS hacking with IE, check out Essentials of CSS Hacking For Internet Explorer by Marko Dugonjic. For more info on CSS standards support in modern browsers, check out Web Browser Standards Support by David Hammond.

Removing the TABLE from the CreateUserWizard control

About two months ago, I wrote a post about removing the TABLE from ASP.Net 2.0’s Login control. The below code will let you do the same from the CreateUserWizard control. One important caveat: for this to work (in my limited testing), you must provide a custom template for the ContentTemplate and CustomNavigationTemplate of the CreateUserWizardStep, and for the ContentTemplate of the CompleteWizardStep.

public class CssCreateUserWizard : System.Web.UI.WebControls.CreateUserWizard
{
    protected override void Render( HtmlTextWriter writer )
    {
        if ( CreateUserStep.ContentTemplate != null && this.ActiveStep == this.CreateUserStep )
        {
            WebControl creatediv = new WebControl( HtmlTextWriterTag.Div );
            creatediv.CssClass = this.CssClass;
            CreateUserStep.ContentTemplate.InstantiateIn( creatediv );
            CreateUserStep.ContentTemplateContainer.Controls.Clear();
            CreateUserStep.ContentTemplateContainer.Controls.Add( creatediv );
            creatediv.RenderControl( writer );

            if ( CreateUserStep.CustomNavigationTemplate != null )
            {
                WebControl navdiv = new WebControl(HtmlTextWriterTag.Div);
                navdiv.CssClass = this.CssClass;
                CreateUserStep.CustomNavigationTemplate.InstantiateIn(navdiv);
                CreateUserStep.CustomNavigationTemplateContainer.Controls.Clear();
                CreateUserStep.CustomNavigationTemplateContainer.Controls.Add(navdiv);
                navdiv.RenderControl(writer);
            }
        }

        if ( CompleteStep.ContentTemplate != null && this.ActiveStep == this.CompleteStep )
        {
            WebControl completediv = new WebControl( HtmlTextWriterTag.Div );
            completediv.CssClass = this.CssClass;
            CompleteStep.ContentTemplate.InstantiateIn( completediv );
            CompleteStep.ContentTemplateContainer.Controls.Clear();
            CompleteStep.ContentTemplateContainer.Controls.Add( completediv );
            completediv.RenderControl( writer );
        }
    }
}

Removing tables in Microsoft’s ASP.Net 2.0 Controls

Microsoft has been touting ASP.Net 2.0 as taking great strides towards XHTML compatibility and meeting common accessibility guidelines. However, some controls still add table tags around them, despite your best efforts to avoid using tables. The new Login control is one of those.

For me, the table wrapper around the Login control was causing rendering problems. I was using a pure CSS layout with no tables for the login form, and the presence of the table tag wrapped around the control was breaking my layout. A quick Google search (q=asp.net+2.0+login+control+table) found a blog post that outlined a solution.

The fix was simple: create a new class, inherit from the existing System.Web.UI.WebControls.Login class, and override the Render method. A few lines of code, and the table wrapper was replaced with a div wrapper. There was one catch: the version posted on the aforementioned blog didn’t include the CssClass attribute on the new control. One extra line of code fixed that.

Below is the code, all but one line thanks to Alex Gorbatchev of dreamprojections.com:

    public class CssLogin : System.Web.UI.WebControls.Login
    {
        protected override void Render( HtmlTextWriter writer )
        {
            WebControl div = new WebControl( HtmlTextWriterTag.Div );

            LayoutTemplate.InstantiateIn( div );

            Controls.Clear();
            Controls.Add( div );

            div.CopyBaseAttributes( this );
            div.CssClass = this.CssClass;
            div.RenderControl( writer );
        }
    }