Dirk Bergmann

Developer, panographer. Does consultancy work from own company. Lives in Chiang Mai, Thailand.

Twitter

Chiang Mai

Hua Hin

Thailand Hotels

ListVote - List. Vote. Learn.

Partnerseek - Find Partners

Selecting and Submitting the Entire List Item

Note: this article uses jQuery, Ruby on Rails and CSS. It might be useful for other combinations.

You have a list of products and don?t want to force users to search for the link to the details page. Rather, give him some hover effect for each list item and let him click anywhere on the item. The list here is displayed as an unordered list (UL), but a similar technique should work with table rows (TR), divs or other block elements.

Several techniques are applied here:

Step 1: Turn the cursor into a pointer:

.list_item {cursor:pointer}; (believe it or not, WORKS in IE6!)

Step 2: Re-style the list item when the cursor is over it:

Civilized browsers, use the :hover pseudo element:

.list_item:hover {background-color:#a1a1a1}

That abomination from hell, IE666, use JavaScript, here?s a snippet for jQuery, note the syntax of the css function:

$(document).ready(function(){ 
$('.list_item').mouseover(function(){
      $(this).css({'background-color':'#a1a1a1'})
        }
)
      .mouseout(function(){
          $(this).css({'background-color':'#1a1a1a'})
      }
);
});

Or even better, get the prior color and reset on mouseout:

$(document).ready(function(){
var orig_bg;
$('.list_item').mouseover(function(){
orig_bg = $(this).css('background-color');
      $(this).css({'background-color':'#a1a1a1'})
        }
)
      .mouseout(function(){
          $(this).css({'background-color':**orig_bg**})
      }
);
});

Step 3: Bind the click event to every list item:

As every list item likely has a link to the details  page, pilfer the url from there, no need to dig into the Rails routes. Here?s the jQuery code:

$(document).ready(function(){
$('.list_item')
.click(function(){
//now $(this) refers to the current list_item element, dig deeper with .find() to get the :link " var details_link = $(this).find('a#details_link')[0].href;
//do the ?redirect?:
     parent.location.href = details_link;
}
)   
});

Summing up, this is all pretty easy thanks to the power of jQuery. There was no need to use Rails? div_for to get to the product links or generate them, just get everything out of the DOM. There might be a leaner, DRYer or easier way to do this, if you know better, please post a comment.