Friday, February 13, 2009

Using 'esc' to close dynamic modal dialogs

In my previous post I described how to get a reference to a behavior when you know the target control (speaking in terms of the Ajax Control Toolkit extenders) of the extender. This is necessary to be able to call the hide() method of the ModalPopupExtender when the 'esc' key is pressed.

With this knowledge and jQuery we can get a handle on each of the ModalPopupExtender behaviors in a databound repeating control (such as GridView or Accordion.)

jQuery can be used to get a set of DOM objects by class. I want to get the set of DOM objects that represent the target controls of all the ModalPopupExtenders in the page. In order to facilitate this, I set the CssClass property of all the target controls to "mpeTarget". It's important to remember that it's possible to set multiple classes for the same element by separating them with a space, so if your target control already has a class assigned to it you can still add "mpeTarget". Your class or CssClass property would then look like CssClass="myExistingClass mpeTarget"

Now that all the target controls have been given a CssClass to distinguish them, we are ready to write some javascript.

        function pageLoad(sender, args) {
            if (!args.get_isPartialLoad()) {
                $addHandler(document, "keydown", onKeyDown);
            }
        }


This sets up the document to respond to the "keydown" event by calling a function named "onKeyDown" which is shown here:

        function onKeyDown(e) {
            if (e && e.keyCode == Sys.UI.Key.esc) {
                $(".mpeTarget").each(function() {
                    var mpe = Sys.UI.Behavior.getBehaviorsByType(this, AjaxControlToolkit.ModalPopupBehavior);                    
                    if (mpe.length > 0)
                        mpe[0].hide();
                });
            }
        }


This method checks to see if the pressed key is the 'esc' key. If it is, jQuery is used to iterate through all the DOM objects with css class "mpeTarget". Each of those DOM objects is used in a call to getBehaviorsByType() to get the behavior object and then call its hide() method.

No comments:

Post a Comment