- Javascript

How to add Keyboard Navigation to ASP.NET DataView

Check out this how-to add keyboard support to an ASP.NET DataView. The keyboard support helps you increase both web site usability and accessibility.

The following sample can also be viewed online here. In fact, you can download it and run it locally using CodeCentral.

To add keyboard support, you’ll need to add some client-side functionality to the ASPxDataView. Specifically, the client-side keydown event.

In the code below, the following keys are processed:
  * Left Arrow (activates a previous page)
  * Right Arrow (activates the next page)

Add the following script code to the <Head> section of your html page that contains your ASPxDataView. You can also add the code to a separate file but be sure to reference it in the page that contains the ASPxDataView.

Note: The AttachEventToElement method of the ASPxClientUtils class is used to subscribe to a document keydown event. The PerformCallback method call of the ASPxClientDataView class is used to raise the ASPxDataView’s Callback event to change the active page of ASPxDataView on the server side:

var dataviewPerformingCallback = false;

function AddKeyboardNavigationTo(dv) {
    dv.BeginCallback.AddHandler(function (s, e) { dataviewPerformingCallback = true; });
    dv.EndCallback.AddHandler(function (s, e) { dataviewPerformingCallback = false; });
    ASPxClientUtils.AttachEventToElement(document, "keydown",
        function (evt) {
            return OnDocumentKeyDown(evt, dv);
        });
}

function OnDocumentKeyDown(evt, dv) {
    if (typeof (event) != "undefined" && event != null)
        evt = event;
    if (NeedProcessDocumentKeyDown(evt) && !dataviewPerformingCallback) {
        if (evt.keyCode == ASPxKey.Left /*37-Left Arrow*/) {
            if (dv.cpPageIndex > 0)
                dv.PerformCallback('Prev');
            return ASPxClientUtils.PreventEvent(evt);
        } else if (evt.keyCode == ASPxKey.Right /*39-Right Arrow*/ && dv.cpPageIndex < dv.cpPageCount - 1) {
            dv.PerformCallback('Next');
            return ASPxClientUtils.PreventEvent(evt);
        }
    }
}

function NeedProcessDocumentKeyDown(evt) {
    var evtSrc = ASPxClientUtils.GetEventSource(evt);
    if (evtSrc.tagName == "INPUT")
        return evtSrc.type != "text" && evtSrc.type != "password";
    else
        return evtSrc.tagName != "TEXTAREA";
}

Attach the ‘AddKeyboardNavigationTo’ method to the ASPxDataView’s Init event in the Page_Load of the code behind:

using System;
using DevExpress.Web.ASPxDataView;
using DevExpress.Web.ASPxClasses;

public partial class _Default : System.Web.UI.Page {
    protected void Page_Load(object sender, EventArgs e) {
        ASPxWebControl.RegisterUtilsScript(Page);
        ASPxDataView1.ClientSideEvents.Init = "function(s, e) { AddKeyboardNavigationTo(s); }";
    }

Finally, be sure that the ASPxDataView's ClientInstanceName property is defined:

<form id="form1" runat="server">
    <div>
        <dx:ASPxDataView ID="ASPxDataView1" runat="server" DataSourceID="AccessDataSource1"
            RowPerPage="1" ClientInstanceName="dataview" OnCustomCallback="ASPxDataView1_CustomCallback"
            OnDataBound="ASPxDataView1_DataBound">
            <ItemTemplate>
                <b>EmployeeID</b>:
                <asp:Label ID="EmployeeIDLabel" runat="server" Text='<%# Eval("EmployeeID") %>' />
                <br />
                <b>LastName</b>:
                <asp:Label ID="LastNameLabel" runat="server" Text='<%# Eval("LastName") %>' />
                <br />
                <b>FirstName</b>:
                <asp:Label ID="FirstNameLabel" runat="server" Text='<%# Eval("FirstName") %>' />
                <br />
                <b>Title</b>:
                <asp:Label ID="TitleLabel" runat="server" Text='<%# Eval("Title") %>' />
                <br />
            </ItemTemplate>
        </dx:ASPxDataView>
    </div>
    <asp:AccessDataSource ID="AccessDataSource1" runat="server" DataFile="~/App_Data/nwind.mdb"
        SelectCommand="SELECT * FROM [Employees]"></asp:AccessDataSource>
</form>

Try the sample online at CodeCentral.

This great keyboard functionality is also built-in to the ASPxTreeList and ASPxGridView.

Drop me a line below with any questions. Thanks!

Follow MehulHarry on Twitter

DXperience? What's That?

DXperience is the .NET developer's secret weapon. Get full access to a complete suite of professional components that let you instantly drop in new features, designer styles and fast performance for your applications. Try a fully-functional version of DXperience for free now: http://www.devexpress.com/Downloads/NET/


Friday Focus 08/27/10: (Mostly) Black and White

I’ve noticed a lot of designs with a mostly black and white color palette lately, and not just for site types you’d expect. Is the colorful, rainbow trend being phased out with something more classic? Are people tired of safe, middle-ground gray? Welcome to this week’s Friday Focus.

Designs of the Week

Quartel Design

It’s interesting how even the background is a strong black and white graphic.

Larissa Meek

Lots of other trends here: folded ribbons, subtle noise texture, and centered logo. Note how the social buttons and feed subscriber count come before the navigation; guess that’s what’s more important on this site!

Simple Square

Just as simple and minimal as the color palette.

Little Black Dress Society

Love the hanger icon on the current navigation item, and the feather in the drop-down menu.

David Perel

Yellow as accent for black and white designs start here. And are you for or against sidebars?

iFontMaker

Screenshots and product shots are getting bigger and bigger. I vaguely remember them occupying one-third of the page but now it’s half.

Made By Water

I like how light and playful this looks, including the irregular pattern in the background, and the recurring circles.

Elementic-Interactions

Great breathing space between everything.

Eric Johansson

It’s so clever how when you hover over the a navigation item at the top, it also affects the navigation at the bottom (not pictured). Also note how the browser frame in the portfolio carousel is abstracted and black.

Quotivate Me

The amount of gradients here is a little strong but I think it works. Perhaps it’s just the text in the lower half that could be improved.

Bombardier Studio

A little bit of alignment issue but as usual I love the whitespace.

Keith Bates

Still not a big fan of the noise texture trend but it’s slowly warming up to me. Here it looks warm and fuzzy!

Monsoon Company

The post navigation here is a wonderful idea, but the arrows could be a little more obvious and closer to the center post.

dodaqueen.com

What a nice idea to put the slideshow on the top right across vertical navigation, and place your name big front and center. Memorable branding.

Build Conference

I love how the nut on the logo repeats on the ticket icon.

KISSinsights

The video area doesn’t really work for me but everything else looks nice.

Paper Wireframes

More and more I’m seeing a layout divided in halves instead of in thirds.

The Jacket Room

The design is compelling although as a website design, not so much. I would have loved to see more.

Jose Luis Merino Parra

The mix of patterns and the interactions feels nice, but I don’t understand why you have to hover twice to navigation: first to make the designer name appear, then to make the menu appear.

Telegramme Studio

Big, bold, but still clean and easy to read.

Social Media Weekly

Accessibility How do we save longdesc?
“The longdesc attribute, although potentially useful, was removed from the HTML5 specification, despite recommendations to retain it from the HTML Accessibility Task Force.”

UsabilityDarkPatterns.org
“This pattern library is dedicated to Dark Patterns: user interfaces that have been designed to trick users into doing things they wouldn’t otherwise have done.”

Usability You’re a failure: Deal with it
“Every website has points of failure. It is inevitable. The question is do you know what they are and are you doing something about them?”

CSSCSS3 Playground by Mike Plate
WYSIWYG CSS3 code generator.

JavaScriptPaintbrushJS
“A lightweight browser-based image processing library”


Minimise file size with the YUI Compressor TextMate Bundle

It’s quite obvious that the smaller the files that make up your website are, the less time your visitors will wait for them to download. One way of reducing file sizes is minimising JavaScript and CSS files by removing comments and whitespace, among other things.

To do that, you can either let the server do it for you or minimise the files yourself before uploading them to the server. Letting the server do it automatically is probably the most convenient way since you don't have to remember to do it. But it isn't practical or possible for everyone to use something like minify, so sometimes you'll need to do it manually.

That may sound like more trouble than it's worth. Luckily for us TextMate users there's a handy YUI Compressor TextMate bundle that makes it almost as transparent as the server-side solution.

Read full post

Posted in , , .



jQuery Plugin Checklist: Should You Use That jQuery Plug-In?

Smashing-magazine-advertisement in jQuery Plugin Checklist: Should You Use That jQuery Plug-In?Spacer in jQuery Plugin Checklist: Should You Use That jQuery Plug-In?
 in jQuery Plugin Checklist: Should You Use That jQuery Plug-In?  in jQuery Plugin Checklist: Should You Use That jQuery Plug-In?  in jQuery Plugin Checklist: Should You Use That jQuery Plug-In?

jQuery plug-ins provide an excellent way to save time and streamline development, allowing programmers to avoid having to build every component from scratch. But plug-ins are also a wild card that introduce an element of uncertainty into any code base. A good plug-in saves countless development hours; a bad plug-in leads to bug fixes that take longer than actually building the component from scratch.

Fortunately, one usually has a number of different plug-ins to choose from. But even if you have only one, figure out whether it’s worth using at all. The last thing you want to do is introduce bad code into your code base.

[Offtopic: by the way, did you know that there is a Smashing eBook Series? Book #2 is Successful Freelancing for Web Designers, 260 pages for just $9,90.]

Do You Need A Plug-In At All?

The first step is to figure out whether you even need a plug-in. If you don’t, you’ll save yourself both file size and time.

1. Would Writing It Yourself Be Better?

If the functionality is simple enough, you could consider writing it yourself. jQuery plug-ins often come bundled with a wide variety of features, which might be overkill for your situation. In these cases, writing any simple functionality by hand often makes more sense. Of course, the benefits have to be weighed against the amount of work involved.

For example, jQuery UI’s accordion is great if you need advanced functionality, but it might be overkill if you just need panels that open and close. If you don’t already use jQuery UI elsewhere on your website, consider instead the native jQuery slideToggle() or animate().

2. Is It Similar to a Plug-In You’re Already Using?

After discovering that a particular plug-in doesn’t handle everything you need, finding another plug-in to cover loose ends might be tempting. But including two similar plug-ins in the same app is a sure path to bloated JavaScript.

Can you find a single plug-in that covers everything you need? If not, can you extend one of the plug-ins you have to cover everything you need? Again, in deciding whether to extend a plug-in, weigh the benefits against the development time involved.

For example, jQuery lightbox is a nice way to enable pop-up photos in a gallery, and simpleModal is a great way to display modal messages to users. But why would you use both on the same website? You could easily extend one to cover both uses. Better yet, find one plug-in that covers everything, such as Colorbox.

3. Do You Even Need JavaScript?

In some situations, JavaScript isn’t needed at all. CSS pseudo-selectors such as :hover and CSS3 transitions can cover a variety of dynamic functionality much faster than a comparable JavaScript solution. Also, many plug-ins apply only styling; doing this with mark-up and CSS might make more sense.

For example, plug-ins such as jQuery Tooltip are indispensable if you have dynamic content that requires well-placed tooltips. But if you use tooltips in only a few select locations, using pure CSS is better (see this example). You can take static tooltips a step further by animating the effect using a CSS3 transition, but bear in mind that the animation will work only in certain browsers.

Avoid Red Flags

When reviewing any plug-in, a number of warning signs will indicate poor quality. Here, we’ll look at all aspects of plug-ins, from the JavaScript to the CSS to the mark-up. We’ll even consider how plug-ins are released. None of these red flags alone should eliminate any plug-in from consideration. You get what you pay for, and because you’re probably paying nothing, you should be willing to cut any one a bit of slack.

If you’re fortunate enough to have more than one option, these warning signs could help you narrow down your choice. But even if you have only one option, be prepared to forgo it if you see too many red flags. Save yourself the headache ahead of time.

4. Weird Option or Argument Syntax

After using jQuery for a while, developers get a sense of how most functions accept arguments. If a plug-in developer uses unusual syntax, it stands to reason that they don’t have much jQuery or JavaScript experience.

Some plug-ins accept a jQuery object as an argument but don’t allow chaining from that object; for example, $.myPlugin( $('a') ); but not $('a').myPlugin(); This is a big red flag.

A green flag would be a plug-in in this format…

$('.my-selector').myPlugin({
 opt1 : 75,
 opt2 : 'asdf'
});

… that also accepts…

$.myPlugin({
 opt1 : 75,
 opt2 : 'asdf'
}, $('.my-selector'));

5. Little to No Documentation

Without documentation, a plug-in can be very difficult to use, because that is the first place you look for answers to your questions. Documentation comes in a variety of formats; proper documentation is best, but well-commented code can work just as well. If documentation doesn’t exist or is just a blog post with a quick example, then you might want to consider other options.

Good documentation shows that the plug-in creator cares about users like you. It also shows that they have dug into other plug-ins enough to know the value of good documentation.

6. Poor History of Support

Lack of support indicates that finding help will be difficult when issues arise. More tellingly, it indicates that the plug-in has not been updated in a while. One advantage of open-source software is all of the eye-balls that are debugging and improving it. If the author never speaks to these people, the plug-in won’t grow.

When was the last time the plug-in you’re considering was updated? When was the last time a support request was answered? While not all plug-ins need as robust a support system as the jQuery plug-ins website, be wary of plug-ins that have never been modified.

A documented history of support, in which the author has responded to both bug and enhancement requests, is a green flag. A support forum further indicates that the plug-in is well supported, if not by the author then at least by the community.

7. No Minified Version

Though a fairly minor red flag, if the plug-in’s creator doesn’t provide a minified version along with the source code, then they may not be overly concerned with performance. Sure, you could minify it yourself, but this red flag isn’t about wasted time: it’s about the possibility that the plug-in contains far worse performance issues.

On the other hand, providing a minified, packed and gzipped version in the download package is an indication that the author cares about JavaScript performance.

8. Strange Mark-Up Requirements

If a plug-in requires mark-up, then the mark-up should be of high quality. It should make semantic sense and be flexible enough for your purposes. Besides indicating poor front-end skills, strange mark-up makes integration more difficult. A good plug-in plugs into just about any mark-up you use; a bad plug-in makes you jump through hoops.

In certain situations, more rigid mark-up is needed, so be prepared to judge this on a sliding scale. Basically, the more specific the functionality, the more specific the mark-up needed. Completely flexible mark-up that descends naturally from any jQuery selector is the easiest to integrate.

9. Excessive CSS

Many jQuery plug-ins come packaged with CSS, and the quality of the style sheets is just as important as the JavaScript. An excessive number of styles is a sure sign of bad CSS. But what constitutes “excessive” depends on the purpose of the plug-in. Something very display-heavy, such as a lightbox or UI plug-in, will need more CSS than something that drives a simple animation.

Good CSS styles a plug-in’s content effectively while allowing you to easily modify the styles to fit your theme.

10. No One Else Uses It

With the sheer volume of jQuery users, most decent plug-ins will probably have something written about them, even if it’s a “50 jQuery [fill in the blank]” post. Do a simple Google search for the plug-in. If you get very few results, you might want to consider another option, unless the plug-in is brand new or you can verifiy that it is written by a professional.

Posts on prominent blogs are great, and posts by prominent jQuery programmers are even better.

Final Assessment

After you’ve given the plug-in the third degree, the only thing left to do is plug it in and test how well it performs.

11. Plug It In and See

Probably the best way to test a plug-in is to simply plug it on the development server and see the results. First, does it break anything? Make sure to look at JavaScript in the surrounding areas. If the plug-in includes a style sheet, look for layout and styling errors on any page that applies the style sheet.

Additionally, how does the plug-in perform? If it runs slowly or the page lags considerably when loading, it might be important to consider other options.

12. Benchmarking With JSPerf

To take your performance review to the next level, run a benchmark test using JSPerf. Benchmarking basically runs a set of operations a number of times, and then returns an average of how long it took to execute. JSPerf provides an easy way to test how quickly a plug-in runs. This can be a great way to pick a winner between two seemingly identical plug-ins.

Jsperf in jQuery Plugin Checklist: Should You Use That jQuery Plug-In?
An example of a performance test run in jsPerf.

13. Cross-Browser Testing

If a plug-in comes with a lot of CSS, make sure to test the styling in all of the browsers that you want to support. Bear in mind that CSS can be drawn from external style sheets or from within the JavaScript itself.

Even if the plug-in doesn’t have any styling, check for JavaScript errors across browsers anyway (at least in the earliest version of IE that you support). jQuery’s core handles most cross-browser issues, but plug-ins invariably use some amount of pure JavaScript, which tends to break in older browsers.

14. Unit Testing

Finally, you may want to consider taking cross-browser testing even further with unit tests. Unit testing provides a simple way to test individual components of a plug-in in any browser or platform you want to support. If the plug-in’s author has included unit tests in their release, you can bet that all components of the plug-in will work across browsers and platforms.

Unfortunately, very few plug-ins include unit test data, but that doesn’t mean you can’t perform your own test using the QUnit plug-in.

With minimal set-up, you can test whether the plug-in methods return the desired results. If any test fails, don’t waste your time with the plug-in. In most cases, performing your own unit tests is overkill, but QUnit helps you determine the quality of a plug-in when it really counts. For more information on how to use QUnit, see this tutorial

Qunit-example in jQuery Plugin Checklist: Should You Use That jQuery Plug-In?
An example of a unit test run in QUnit.

Conclusion

When assessing the quality of a jQuery plug-in, look at all levels of the code. Is the JavaScript optimized and error-free? Is the CSS tuned and effective? Does the mark-up make semantic sense and have the flexibility you need? These questions all lead to the most important question: will this plug-in be easy to use?

jQuery core has been optimized and bug-checked not only by the core team but by the entire jQuery community. While holding jQuery plug-ins to the same standard would be unfair, they should stand up to at least some of that same scrutiny.

Related Posts

You may be interested in the following related posts:

(al)


© Jon Raasch for Smashing Magazine, 2010. | Permalink | Post a comment | Add to del.icio.us | Digg this | Stumble on StumbleUpon! | Tweet it! | Submit to Reddit | Forum Smashing Magazine
Post tags: , ,


Detecting Screen Orientation in Mobile Web Applications

In this post, I'd like to share a simple and useful javascript trick I've picked up for building mobile web applications that can detect and respond to screen orientation changes. This is a trick that works for tablets, and smart phones that support device orientation changes, including iPads, iPhones, and Android devices, among others.

  • Sponsored Links

  •  

    September 2010
    M T W T F S S
    « Aug    
     12345
    6789101112
    13141516171819
    20212223242526
    27282930  
  • .

    Copyright © 1996-2010 Answer My Query. All rights reserved.
    iDream theme by Templates Next | Powered by WordPress