Showing posts with label jQuery. Show all posts
Showing posts with label jQuery. Show all posts

Friday, November 14, 2014

Refresh/Update jQuery Selector after Ajax or other DOM Manipulation

jQuery Logo

I'm working on a more or less single page app right now. As such, there's a lot of dynamic DOM manipulation. Sometimes, we need to re-evaluate a jQuery selector to get the new set of objects after the DOM has changed.

Typically we've solved this problem by always using the selector to find the children. This became really frustrating in my Jasmine tests where I found myself doing this a lot!

    it("toggles the display of an element", function() {
        var $togglableItem = $('.togglable');
        expect($togglableItem.length).toBe(0);
        
        $button.trigger('click');  
        var $togglableItem = $('.togglable');
        expect($togglableItem.length).not.toBe(0);
        
        $button.trigger('click');  
        var $togglableItem = $('.togglable');
        expect($togglableItem.length).toBe(0);
    });

Even in production code (outside of tests) that can be kind of a pain. I wanted to be able to do something more like this:

    it("toggles the display of an element", function() {
        var $togglableItem = $('.togglable');
        expect($togglableItem.length).toBe(0);
        
        $button.trigger('click');  
        expect($togglableItem.refresh().length).not.toBe(0);
        
        $button.trigger('click');  
        expect($togglableItem.refresh().length).toBe(0);
    });

A Common Solution

I've seen some implementations of a jQuery refresh plugin that look like this:

(function($) {
    $.fn.extend({
        refresh: function() { return $(this.selector); }
    });
})(jQuery);

I have two problems with this approach. First, I don't always have my elements attached to the DOM when I want to do a refresh. In fact, typically in testing, I don't add my test elements to the DOM so I can't just reuse the selector. The selection depends on the parent jQuery object.

Second, I also really enjoy the fluency of jQuery and often make use of .end() method when it makes sense. The approach above flattens the selector stack and .end() returns the default jQuery object.

Preferred Approach

To maintain the fluency of jQuery and allow the refresh, here's what I'm proposing:

(function($) {
    $.fn.extend({
        refresh: function() { 
            var $parent = this.end();
            var selector = this.selector.substring($parent.selector.length).trim();
            return $parent.find(selector); 
        }
    });
})(jQuery);

Caveats

I haven't used this in the wild yet. I know .selector is deprecated, but it's the best I could find for now. It does, however, work pretty darned well in my Jasmine tests. :)

Friday, June 17, 2011

GiantDropdown jQuery Plugin for Styling Large Select Lists

A few months ago, I was working on a performance management application for the Centers for Disease Control. They wanted a select box that contained a list of competencies from which they could compose a template. The problem was some of the items in the list were hundreds of characters long and, at the time of writing, most browsers would behave very badly with drop down boxes of that size.

I was sitting at home that night and decided I could probably come up with a jQuery plugin that would use the select list as the backing field and present a prettier display. I did and we ended up using it at the CDC. I decided I'd share in case anyone else runs into the same issue.

Here's an example of what one of the select boxes would look like:


It's not very pretty and it behaves unpredictably with other DOM elements. With the GiantDropdown plugin, we can style it any way we choose and still preserve all of the original behavior of the select list (meaning, it even works with multi-selects and option groups).

Here are some samples of the giant-ified dropdowns:


If you'd like to get the giant dropdown jquery plugin, the can check out the Giant Dropdown jQuery Plugin Git Repository. Feel free to make improvements.

Thursday, March 11, 2010

Custom jQuery Selector for External and Internal Links

jQuery LogoI was working on a website for my fiancee and her church group called The Diocese of Atlanta Young Adults. They were hosting an event they call the Young Adult Summit.

One of the requirements I had was to provide a warning to users before they left the page by after having clicked an external link. Using jQuery, I was able to bind to the click event with easy cross browser compatibility and I used jQueryUI to open a modal dialog box. Pretty basic stuff.

The one thing I regretted was that I had to use a class name to determine which links were external and which were internal. A few days ago, I discovered that jQuery supports custom selectors and I decided to write a pair of custom selectors for identifying internal and external links.
jQuery.extend(
  jQuery.expr[ ":" ],
  {
    /*
      /:\/\// is simply looking for a protocol definition.
      technically it would be better to check the domain
      name of the link, but i always use relative links
      for internal links.
    */

    external: function(obj, index, meta, stack)
    {
      return /:\/\//.test($(obj).attr("href"));
    },

    internal: function(obj, index, meta, stack)
    {
      return !/:\/\//.test($(obj).attr("href"));
    }
  }
);
I do have a few items of note. First, you'll notice that I'm not actually looking for the current domain name in the links. That's because I use relative links for all of my internal links these days. Thus, I know that if there's not a protocol definition that it's an internal link. If you need to identify internal links by domain as well, you can just pull that out of top.location.href and check for it too.

Second, you could technically use this selector on any DOM object. There are several ways to get around this. One way would be to verify that the object is an anchor tag. Another would be to verify that the href attribute exists. I just plan on using common sense.

Here's a quick usage example:
$("a:external").click(verifyNavigateAway);
$("a:internal").css("font-weight", "bold");