Nerdy Morsel: Focus/Blur Events in Javascript

Tuesday, February 17, 2009, 09:56pm

 

I decided I'd add a little something to my site that I'll call 'Nerdy Morsels'. Working with code all day, I'm bound to stumble on weird stuff here and there that will throw me for a loop and force me into hours of debugging over something insanely simple. Something just like this happened today (though it didn't take me too long to figure out) and I figured I'd share it with you. You might think some of these posts will be the most retarded thing in the world, but likely so do I, but I hope they help someone.

I was working on some MooTools Javascript magic today, applying some events to an <a> tag to animate open a menu:

<a id="btn">Click/blur me for some stuff to happen</a>

Basically I wanted the menu to expand onclick and I was trying to work some trickery to hide it onblur:

window.addEvent("domready", function(){
    $("btn").addEvent("blur", function() {
        // Do some stuff when focus is removed
    });
});

You might already see the problem, but I was setting both 'focus' and 'blur' events with no result, and I ran a few circles trying to figure it out. The simple reason why? I did not set my 'href' property! If you want blur/focus events to occur on a link element, you have to set one! I simply added "href='#'" to the tag and it worked fine. Obviously when you're thorough with your markup you'd almost never have no 'href' property in a link tag, but since I was just using it to trigger an event, I didn't think too much of it.

Simple as that—that concludes my nerdy morsel for the day, hope it was nerd-liscious for you...


 

Comments

There are no comments on this post yet. Get the party started below...


Add a comment

  1. Denotes required field

Recent Tracks

Powered by AudioScrobbler