Monday, February 27, 2012

TextMate-like ⌘T & ⇧⌘T in Chrome Dev Tools & Other New Features

Introduction


For the past year or so I've used Google Chrome Canary as my primary web browser, however, about a month ago I temporarily switched to the stable build of Chrome because of some instability in the dev tools. I just recently switched back to Canary and was pleasantly surprised to see numerous new features in the dev tools there were very welcome indeed!

This post only covers the extreme latest in Chrome Dev Tools. There are so many more rich features that can be found. If you are interested about more helpful features you might be interested in a post I did last year entitled 7 Chrome Tips Developers & Designers May Not Know

If you are not familiar with the Canary build of Chrome, it is a extremely dev version of the browser. You should be cautious because it does update almost every day, but at the same time you get first in line to see all the new features. Unlike the dev or beta builds of Chrome you can actually install Canary side-by-side next to your Stable or Beta build of Chrome. This makes switching between versions very convenient.

The features I am about to describe are currently only available in the dev or canary builds of Chrome. If you have the Beta or Stable builds then you will not see these yet, but hopefully they'll make their way to those builds sooner than later. At least this will wet your appetite ;)

Scripts Explorer


A welcome change to the Scripts tab is a new Scripts Explorer (as seen in the below image). The previous way to navigate through the scripts of a webpage was to open a HUGE drop down containing tons of script files. Chrome kept reorganizing that huge drop-down list to make it more usable, but in the end it wasn't optimal when dealing with a site with lots of JavaScript fiels.

The new Scripts Explorer nicely separates the Scripts used on the webpage from the Content Scripts used in all of the Chrome Extensions you have installed in your browser. Historically, it was slightly annoying to see all those Content Scripts alongside your main JavaScript files in that huge drop down mentioned above. Again, over time Chrome moved those Content Scripts to the bottom of that drop down instead of intermingled, but this move to the Scripts Explorer is head over heals WAY better... YAY!

In addition, you can also choose to dock the Scripts Explorer to the left side of the dev tools (by clicking the little icon in the upper right) or have it auto-close when you are done finding what you need.


TextMate's ⌘T "Go to File" Feature


I don't know about you, but I'm one of those keyboard shortcut junkies, so I am always on the lookout on how to do my job without using the mouse. So, I was even more excited to see support for quickly finding a JavaScript file by only using the keyboard! Chrome call's this feature "Go to Script" and it is similar to what you may have experience in TextMate using ⌘T or maybe in Sublime Text 2 with ⌘P.

Since ⌘T is already reserved for creating a new tab in Chrome, they have chosen ⌘O for this feature. As soon as you type ⌘O you will see the following dialog displaying JavaScript files. As you type the list will filter to only the files that match what you are typing. You can arrow up or down to narrow the selection even more and then click "enter" to open that script file.


TextMate's ⇧⌘T "Go to Symbol" Feature


Now, if the "Go to Script" feature wasn't enough, there is also the "Go to Function", which is similar to the "Go to Symbol" feature of TextMate using ⇧⌘T or ⌘R in Sublime Text 2.

Once you are in a JavaScript file you can press ⇧⌘O to bring up the "Go to Function" dialog. This works in a very similar way as the "Go to Script" dialog as we saw previously, but this time instead of looking for files, it helps you track down functions! Navigating through your JavaScript files to find a specific function has now become a breeze!


Dock Dev Tools to the Right


The last feature that stood out to me as really cool, was the new setting to "Dock to right". Many people these days have a wide-screen monitor and having the dev tools docked at the bottom of the screen sometimes feels a little scrunched. If I have my browser maximized there is usually tons of room to the left or right of the website I am viewing.

Thankfully, with this new feature I can now choose to dock the dev tool to the right of my screen to give some breathing room for development!

Note: I undrestand some like to undock the dev tools to solve this issue, but I usually tend to like keeping them docked so this new feature is very handy for me.


In order to turn on this feature, you'll need to go into the Settings dialog. You can access this by clicking on the gear icon located at the bottom right of your dev tools. Once the dialog has been launched you should see a General section with the "Doc to right" option listed.


Conclusion


I find the the above JavaScript enhancements to the dev tools have really made navigating through scripts to be much more enjoyable. If you have noticed any other new features that I have missed please let me know. They keep cropping up all the time... which is AWESOME!

If you have Chrome Canary then you can start using the above features right way, otherwise they should make it in a Beta or Stable build in the near future.

Monday, February 13, 2012

Find the jQuery Bug #4: Animations Gone Wild

Introduction


In this open-ended series I'll be showcasing a snippet of buggy jQuery code that you might encounter, explain what the problem is, and then identify how you can easily resolve the issue.

You can view other posts in this series...

The Desired Feature


We want to take the following HTML and build a simple jQuery menu that will reveal sub-menus when you hover over each item.


The Buggy Code


The following code snippet is our first attempt at solving the problem, but there is a subtle error. Do you see it?


If you start playing with the menu it appears that it works as intended, but as you continue to use the menu an annoying problem raises its ugly head. If you move your mouse really quick from right to left over the menu you'll see the problem :(



The Underlying Problem


If you played with the example above you'll have noticed that if you interact with the menu really quickly side-to-side then the animations continue over and over and over again, even after you've moved off the menu completely!

At the root of the problem is an animation queue that has gotten out of hand. jQuery keeps an internal queue to help it know what animation to run next. When you take an element and call one of the animation methods ( .animate(), .slideDown(), .slideUp(), .slideToggle(), etc... ) what really happens is that effect gets added to the default "fx" animation queue that is attached to the element. As each effects completes jQuery will move on to the next effect in the queue until all animations are complete.

The magic that we need is to somehow interrupt the queue system. Thankfully, there is an API just for that and in the next section we will show how to use it.

A Solution


The solution to fix this problem is really simple and straightforward. In the words of Bob Newhart, we need the animation to STOP IT!

Of course, we can tell our program to STOP IT!, but they are usually to stubborn to heed to our warnings. Thankfully there is a method we can utilize in jQuery coincidentally called .stop() which we can use to solve our animation problem!

The following is the documentation from jQuery's website about the .stop() method that we will use.

.stop( [clearQueue] [, jumpToEnd] )
version added: 1.2
clearQueue - A Boolean indicating whether to remove queued animation as well. Defaults to false.
jumpToEnd - A Boolean indicating whether to complete the current animation immediately. Defaults to false.

.stop( [queue] [, clearQueue] [, jumpToEnd] )
version added: 1.7
queue - The name of the queue in which to stop animations.
clear - QueueA Boolean indicating whether to remove queued animation as well. Defaults to false.
jumpToEnd - A Boolean indicating whether to complete the current animation immediately. Defaults to false.

--http://api.jquery.com/stop/

As you see above there are 2 "overloaded" methods both with optional parameters. The important parameters that we will use to fix our code snippet are the clearQueue and jumpToEnd booleans. In order to get rid of the huge queue of animations on an element and complete whatever animation that was started all we need to do is pass true as both parameters... $element.stop( true, true )!


If you test out the code again below you'll notice that it works just as before, but this time the bug we found when moving our mouse quickly back and forth across the menu is now gone!



A Fancy Solution


If we wanted to get fancy, we could choose to update the animation easing algorithm. An easing algorithm is a mathematical equation that defines the animation path of an effect. Wow, that was a mouth full. Let's try that again, but this time with something visual. The following demo, from jQuery UI, is a great visualization of the various easing algorithms. Click the image to launch the jQuery UI Easing Demo and then click on each square to view the easing in action. I think my favorite is "easeOutBounce" ;)


With these easing options in mind, let's update our example above and use "easeOutBounce" instead of the default "swing" option that is default in jQuery.

NOTE: "The only easing implementations in the jQuery library are the default, called swing, and one that progresses at a constant pace, called linear."

-- http://api.jquery.com/slideDown


You might notice that I also added some other parameters to the .slideDown() and .slideUp() methods. All of the parameters are optional, but if we want we can provide our own values such as a duration, easing algorithm, and a callback to invoke when the animation is complete. In the code above, I trigger a custom event depending if the sub-menu was opened or closed and then I delegate to those events using the .on() method on line 19.

.slideDown( [duration] [, easing] [, callback] )
version added: 1.4.3
.slideUp( [duration] [, easing] [, callback] )
version added: 1.4.3
duration - A string or number determining how long the animation will run.
easing - A string indicating which easing function to use for the transition.
callback - A function to call once the animation is complete.

-- http://api.jquery.com/slideDown/ & http://api.jquery.com/slideUp/

Now you can test the changes we made. The effect may be too adventurous for most production business web applications, but the one I chose is just one of the many easing algorithms provided by jQuery UI that you can pick from. Also, if you are a math wizard you can come up with your algorithm!



Refactoring the Code


If you are anything like me you probably noticed a code smell. Much of the code from the previous examples looks very redundant. Let's take a stab at refactoring the code somewhat to reduce the "duplicated code" smell and made the code DRY (don't repeat yourself).

If you look through your vast code base, And notice code repeated here and there.
You might consider refactoring soon, Or you'll experience maintenance despair!

Previously we were passing two functions to the .hover() method. The 1st function parameter was to handle mouseover events and the other was to handle mouseout events. Thankfully, there is another "overloaded" version of .hover() that takes just 1 function parameter. This 1 function will be invoked on both mouseover events and mouseout events!


You may also notice that we are using a different method to actually perform the sub-menu animation. jQuery includes a .slideToggle() method that will either .slideDown() or .slideUp() depending on the state of the element.

The last thing to take into consideration is how to know which custom event to trigger. Previously I knew which event to trigger because opened was associated with .slideDown() and closed was associated with .slideUp(), but what about now? Thankfully that is easily solved by looking at the event object passed to the hover event handler. The event object has a type property which tells what type of event was originally fired. So, I can do something like this... e.type === "mouseover" ? "opened" : "closed" -- http://jsfiddle.net/ujsfH/

Conclusion


The key concept to remember here is that jQuery has an internal animation queue that you should be aware of. If you need to clear out that queue you can use the .stop() method. Also, you can modify the duration of animation, change the animation easing algorithm, and also respond to an event when the animation is complete.

Things we didn't cover in this post are how to create your own queue, how to create your own easing algorithm, how to modify the default animation duration, and several other concerns.

Until next time...

NOTE: The CSS I used as the base for the example menu above is a modified version from a blog post on @Kriesi's website. I removed the hover styles and replaced his jQuery code with mine for this Find the jQuery Bug post.

Wednesday, February 08, 2012

Regular Expressions in CoffeeScript are Awesome

Let's face it, regular expressions aren't for everyone. It takes a special breed of developer to actually enjoy writing regular expressions. Although I enjoy them, the developer that comes after me may find that they are cryptic and hard to read. And yes, sometimes it takes me a little bit to decipher through an old regular expression that I wrote a while ago.

Take for example, the following regular expression. Can you tell what it is doing? If so... then great, but what about the developers you work with?


One of the very cool things I like about CoffeeScript is that you can annotate your regular expressions! The following snippet of CoffeeScript compiles down to the equivalent JavaScript as seen in the above code sample. Yay ;)


Which code sample would you rather maintain? And more importantly which one would your co-worker be more likely to understand?

NOTE: The above email regular expression is very naive in it's logic. I based the above snippet from a Nettuts+ post entitled, 8 Regular Expressions You Should Know. There are much more comprehensive email regular expressions available on the internet, but I used the above one to show the value of annotation.

As a side note, some tools that I find helpful are Grant Skinner's Online RegExr Tool and I sometimes get inspiration for regular expressions at RegExLib.com. What tools or resources do you use for regular expressions?