A Few Quick Tips for qtip2

Q-TipsThe qtip2 library for jQuery is a handy way of adding tooltips to your website. It has a healthy array of configuration options and event callbacks. That said, every once in a while you have to do something a little less obvious with it.

For example, our customer wanted a tooltip to appear on a user-triggered event, then stay for three seconds — after which time it would disappear for good. After digging around in the qtip docs for a bit, we decided to show the tooltip and then forcefully hide it after three seconds. We also eliminated the jQuery events which trigger show and hide (mouseenter and mouseleave), and set the hide event to be fixed, which was also required to keep the tooltip from disappearing.

var qtip = $(elem).qtip({
  content: 'hello world',
  // ...
  hide: {
    fixed: true,
    event: ''
  },
  show: {
    event: ''
  }
});
qtip.qtip('api').show();
window.setTimeout(function () {
  qtip.qtip('api').hide();
}, 3000);

After seeing it in action, the customer decided that after the initial three-second display, future hovers over the associated element should also pop up the tooltip; and after the mouse moves off the element, the tooltip should disappear immediately. My first attempt to solve this was all wrong — creating a ‘preventHide’ variable which I set to false in three seconds, hooking into the hide event, and stopping it from hiding if ‘preventHide’ is true. It worked, but it wasn’t elegant. And I had to add code to deal with edge cases like entering or leaving the element during the three seconds.

After a bit of digging, I discovered qtip2’s set function. This handy little gem lets you alter the configuration of your qtip after the fact:

$(elem).qtip('api').set({'option': 'value'});

I realized all I needed to do was change the value of the delay for the hide configuration to zero after the three seconds have passed. Voila! Problem solved:

window.setTimeout(function () {
   $(elem).qtip('api').set({'hide.delay', 0});
}, 3000);

Be careful, though. My first attempt caused an exception:

$(elem).qtip('api').set({
    hide: {
        delay: 0
    }
});

This won’t work because set doesn’t merge into your existing config; it merely stomps every key it’s given. You can access specific sub-keys by concatenating keys with a period.

It turns out our final solution after the customer’s requested change was shorter than our first solution. For me, there are few better feelings as a programmer than when you augment code but also manage to make it shorter and cleaner.

What other code-prettifying tips have you come across lately?