Forgot your password?

Home > About Us >Modern Signal Blog

Modern Signal Blog

News, tips, tricks and discussions related to web strategy, web design, and custom web application and database development.

Viewing posts for topic: "jQuery". View all posts.

Colorify: A Simple jQuery Plugin

I recently created a fun little weekend project (well, an MLK Day project to be more specific).  It's a simple survey to query users about what colors come to mind when they think about abstract ideas.  It's called What Color Is...?  The original motivation behind the site was to come up with an idea for my daughter's science fair project.  She sees letters and numbers as colors (something called grapheme-color synesthesia).  I came up with the idea to devise a simple test to see what colors, if any, most people see when they think about an abstract idea.  From there I naturally began thinking about how it could be turned into a slick online survey.  It was an interesting little project that had a number of minor technical challenges along the way.

A Touch of Eye-candy: Colorify jQuery Plugin

For the design of the site, I chose a basic gray jQuery UI theme (Smoothness).  I did this so as to not distract from the main point of the survey by putting too much color into the surrounding UI.  I did feel like adding a little bit of fun color into the UI though.  I decided that when I would put in some multicolored text in the page titles.  To achieve this, I ended up creating a simple jQuery plugin that takes any element and assigns a string of random colors to the letters in the text.  I called it "colorify":

(function($){
    $.fn.colorify = function(){
        var cify = function(s){
            var rgb = function(){
                var i = Math.floor(Math.random() * 3);
                var r = function(n){
                    return n == i ? 0 : Math.floor(Math.random() * 256);
                }
                return "rgb(" + r(0) + "," + r(1) + "," + r(2) + ")";
            }
            var s2 = "";
            for (var i = 0; i < s.length; i++) {
                s2 += "<span style=\"color:" + rgb() + ";\">" + s.substr(i, 1) + "</span>";
            }
            return s2;
        }
        this.html(cify(this.html()));
    };
})(jQuery);

This goes through each letter in the text, gets a random RGB value and assigns it to the letter by wrapping a span tag with a style parameter around the letter.  It's used like any simple jQuery plugin:

$("#wcititle").colorify();

Which creates colored text like this:

What Color Is...?

One interesting thing about this is that my first attempt at the function resulted in some colors that were just too light to show up well on a white background.  That's an obvious problem when getting completely random colors.  The solution I found was to randomly choose one of the 3 color components (R, G, or B) and set that to 0 (full saturation).  This preserves the generation of bright colors without making them too light.

I wouldn't call this a very useful plugin -- I'll probably never use it for another project.  But it was kind of fun to write.  Check it out in action at What Color Is...?

Avoiding Double Submit of Form in ASP.Net

I just implemented something that should have been simple, and actually is simple, but which ended up being a bit more of a struggle than it should have been.

We have a site where occasionally we were getting duplicate payment transactions when people submitted orders.  The transactions were all within a couple seconds of each other, so it appeared that people were just double-clicking the submit button (despite, of course, a message on the page saying to only click the button once).  We did, once upon a time, have javascript code in place that disabled the submit button when it was clicked once, but that code has been removed somewhere along the line.  I think it had been disabled due to the difficulty of dealing with client side validation -- i.e. if the client-side validation failed, the button should not be disabled, because then the user will not be able to submit the form.

I found a variety of posts online about dealing with this problem.  The basic solution is simple, which is to insert code into the form submit handler that runs the client-side validation and only disables the button if it passes.  First I set up this javascript function:

<script type="text/javascript">
    function handleSubmit() {
        if (typeof (ValidatorOnSubmit) == 'function' && ValidatorOnSubmit() == false) {
            return false;
        } else {
            $("form#aspnetForm input[type=submit]")
                .click(function() { return false })
                .fadeTo(200, 0.5);
            return true;
        }
    }
</script>

Then in the page's code behind, I registered the onsubmit function like so:

Page.ClientScript.RegisterOnSubmitStatement(Me.GetType, "OnSubmitScript", "return handleSubmit()")

The javascript function runs the same code that ASP.Net automatically runs for client-side validation, and, if the validation passes, uses jQuery to disable the submit button and fade its appearance.  The fading isn't necessary, but since it's so easy to do with jQuery, why not?

There is one thing in there though, that threw me for a loop.  Most of the posts I found online set the disabled parameter for the button, which you could do with jQuery like this:

$("form#aspnetForm input[type=submit]").attr("disabled", "disabled");

But when I did that I found that the submit action tied to the button no longer fired on the server side.  After puzzling over this for a while, I realized that when the button is disabled, the button value is no longer sent along with the form parameters, and thus the server-size click event for the button is not fired.  I wasn't able to find any references to this problem online (hence the impetus for this blog post).  So instead of using the disabled parameter, I set the click event of the button to return false, which seems to work well.

Something else that I like about this solution, is that it is very generic.  Since I use a generic selector to get the submit button ("form#aspnetForm input[type=submit]"), the javascript function could be included in a site-wide javascript library, and the onsubmit function could be registered in a master page to enable this functionality for all submit buttons on a site.  I'm not ready to do that on this site, since I just want to make sure the order checkout works well for now, but it's nice to know that if this comes up again, I can fix it in a flash.

Tokenized Auto-Complete jQuery Plugin

This post is related to the tokenized auto-complete jQuery plugin available at http://loopj.com/2009/04/25/jquery-plugin-tokenizing-autocomplete-text-entry/.  It is a great plugin.  There are several comments in the discussion on that page regarding the following mods to the plugin. 

  • Use of local filtering instead of AJAX.  This makes sense when you have a smaller, pre-defined list of values to select from.

  • Only allowing a token to be selected if it is not already in the list of selected tokens.

It took me a few hours to update the plugin to implement these mods, so I wanted to share the results.

Here is a demo of the plugin modified to for the above items.  Ideally, the plugin would be updated to allow local and remote lookups.  However, I did not have time to implement in this manner, so my version solely works for local lookups.

View Demo

Complex Styled Menu with jQuery

I recently finished a redesign project, and there were some interesting challenges that came up that I thought I would write about.

To start off, there were the menus.  The site has an obligatory drop-down menu at the top, and a similarly styled menu on the left.  Here's a look at the drop-down menu:


As you can see the items in the menu have a little caret on the left, they turn a darker gray on mouseover, and certain items (members-only ones) have a special star icon on the right.  There are also submenus with the same style.  I'm not going to talk about the specific javascript implementation that I used for the drop-down (I used a slightly modified version of the jQuery plugin jdMenu to get it done -- http://jdsharp.us/jQuery/plugins/jdMenu/), but will instead address how the styles are implemented, which was a bit trickier than you might think.

The html for the menu is a simple nested unordered list:

<ul>
  <li><a href=[url]>20 Clubs</a></li>
  <li><a href=[url] class=star>Build-PAC Contributors</a>
    <ul>
      <li><a href=[url] class=star>BUILD-PAC Fundraising</a></li>
      ... etc ...
    </ul>
  </li>
  ... etc ...
</ul>

Nice and clean and accessible.  But the style has to be pixel perfect too, of course.

When I got the menu from the designer, the caret and the star were implemented with a single background image.  That made sense to some extent.  You can only have one background image per element.  And I can't use the <li> for one of the background images because the only elements that supports the hover is the <a> tag.  And I needed to use the a:hover css selector to make the items turn dark gray on mouseover.

Fine.  But that really makes things a bit complicated and inflexible.  What if I need to adjust the width of the menus (which did indeed happen several times during the redesign)?  I would then need to recreate those background images with the correct width.  I know just enough Photoshop to do that kind of thing, but it's really annoying.

Finally it occurred to me that there's really no reason that the <a> tag is the only one that can do a hover.  With javascript, I could capture the hover for any element.  What is more, jQuery made this very easy to do.  I added this to my page:

$("td.leftnav ul li").hover(function(){
    $(this).addClass("hover")
  },function(){
    $(this).removeClass("hover")
})

(Okay that bit of code applied to my left navigation menu.  jdMenu actually took care of this for my top nav by adding a "jdm_hover" class.)

So with that little bit of code, I was free to set the caret as the background of the <li>, and set the star as the background of the <a>, and let the hover of the <li> take care of the background color change.  And when I inevitably got that call to change the width of the menus, it was a simple change in the stylesheet.

RSS Feed

Testimonials

  • I felt as if my company was their only client. They responded to my needs quickly and efficiently despite short turn around time and intense demands.

    - Teaching Strategies, Inc.

  • I love working with Modern Signal! Their CMS is very easy to use and they are incredibly responsive to questions or challenges I bring them.

    - NALP

  • We wouldn’t have gotten where we are today without your support over the years.  Modern Signal has always been a great partner to us.

    - Kirk Gillis, Managing Director at Zoom Tanzania

  • Modern Signal worked with us to understand our needs and figure out what solution would work best for us. Our Lighthouse CMS is perfectly suited to our website goals. When we later needed to modify the CMS, they again took the time to understand exactly what was  needed and then built that functionality rather than delivering a cookie cutter solution.   

    - Ecosystem Investment Partners

  • Modern Signal has been a great partner for us for over the past 10 years.  As our business grew and our needs changed, Modern Signal was able to work with us to adjust our website platform in the ever-changing online world.  Their service and response level has been second to none, and we've been never been happier with our relationship with them.

    - Charm City Run

  • Modern Signal has a professional staff that was very responsive to our needs during all phases - scoping, developing, implementing and maintaining - of our project.  We have been pleased with their ability to deliver quality work on time and on budget. If given the opportunity, I would work with them again.

    - The National Center for Safe Routes to School

  • This was by far the smoothest website redevelopment I have ever experienced. Modern Signal was a wonderful company to work with and we greatly value our working relationship. 

    - National Association of Student Financial Aid Administrators

  • Modern Signal significantly enhanced our site to be more efficient and user-friendly. They provide excellent customer service with timely and cost-effective solutions.

    - Center for Medicare Education

  • Modern Signal understands our business - from future needs to current limitations - so their solutions are always scalable, solid, and service-oriented.

    - National Association of Home Builders