>
Blog
Book
Portfolio
Search

2/10/2008

5045 Views // 0 Comments // Not Rated

Rendering Divs As Buttons

I'm sure we all know the difference between HTML input controls of type "submit" and "button" with respect to an ASP.NET web form. But just in case you don't, the major different is that submits (which are what ASP.NET buttons ultimately render) will do a post back. Now, nine times out of ten, if you but an actual button on a page, you are going to be posting back.

In modern web design, I feel that buttons, to the user, mean "I'm going to do something" while links mean "I'm going to go somewhere." So given this paradigm, I use buttons for thinks like OK, Cancel, Save, Approve, Reject, etc; the major business verbs used in applications. For everything else, I use link buttons.

But for the first time, last week, I needed a button that COULD NOT post back. We are using the Ajax Control Toolkit animation framework on an internal project, and if you do a post back from within an element that has been animated, it will lose its state. For example, we have a GridView containing a column of Edit buttons. Clicking this button causes the corresponding row to fly out into a square in the middle of the page. It's totally neato burrito, but with one problem: do a click "OK" or "Cancel" on the square and it just disappears!

So we moved as much as we could to client code, and replaced the ASP buttons with HTML buttons, and it worked. However, this little work around didn't last very long. As more and more functionality had to moved client-side, this button had to turn into a div. We needed a place to store the current row's index, and if we put it in the div of the OK button, we could easily access it via the childNodes collection.

So now we had everything running smoothly with tons of JavaScript logic in our fake div buttons. The only problem was the ugly fake div buttons! My esteemed collogue, Arnold Smith, has discovered a brilliantly simple way to get these div HTML elements to look like buttons. Here's an example:

Code Listing 1

  1. <div id="divEdit" runat="server" onclick="ILoveArnold(this);">
  2. <button>Edit</button>
  3. <span style="visibility: hidden;">
  4. <%# Eval("Index") %>
  5. </span>
  6. </div>

Isn't that wild? Sometimes, in code, you get to type exactly what you want to happen!  These button tags will render thier inner text as a normal button on the UI, but as shown above, by using a div, we can insert data-bound items inside of our button. So in the ILoveArnold JavaScript method, we can do a this.childNodes[1].innerText and get the data-bound value for the current row! If things get messy, you can use some creative CSS to keep your button nice and innocent-looking.

Way to go, Arnie!

2 Tags

No Files

No Thoughts

Your Thoughts?

You need to login with Twitter to share a Thought on this post.


Loading...