Blur and Click Events JavaScript

Posted on Posted in Javascript

Just a small blurb about a problem I ran into today that I wanted to pass along.

I have a kind of feature in an app that when you tab off the last element of a row, it gives you a brand new row to work on in the same table. (Think tabular data here). Well, I’m basically listening for the blur event on the last element of the table which also happens to be a button.

Now all of this could have been solved in retrospect by putting the button first but the UI experience would have been terrible, I think. It’s a delete button for the row.

Well, obviously, my first thought is fire the click event and delete the row. No big deal. Well, here is the rub. When firing the click event (particularly on the last row), the blur event fires as well. So the row gets deleted and then immediately put back which is not the intention.

Instead we use the mousedown event. This way I avoid the click event entirely, the delete happens before it ever gets propagated to the blur event. Another way of looking at it is that onclick also triggers a blur after completion. Oh, and in case you were really wondering, the events fire in this order: mousedown, mouseup, onclick.

Side note: There are some really weird things you can come up with on the mouseup event that would be really neat in some game type development for easter eggs, just because people aren’t used to work with mice like that. (Example, clicking somewhere else, holding and dragging the mouse to a specific location and then releasing will trigger an event.)