javascriptjqueryknockout.jsonblur

Prevent firing the blur event if any one of its children receives focus


I have a div on a page that shows some information about a particular category (Image, Name, etc).

When I click on the edit image, it puts the category into edit mode which allows me to update the name. As you can see from the image below, it shows that "Soup" is currently in edit mode, and the others are in normal view mode. This all works as expected with the Cancel / Save buttons doing everything right. (I tried adding an image, but it wouldn't let me, and it needs more love.)

However, once in edit mode, if I click anywhere else on the page (Outside of the div), the expected result would be that the soup category would go back to view mode. Upon an event firing of some sort, this should also allow me to ask if they wanted to save changes.

So then I decided to create a blur event on the "soups" parent div. This works as expected if I click anywhere on the page. However, if I click on the inner element of the div, it also causes the parents blur event to be fired, thus causing the category to go back to view mode.

So, is there a way to prevent the parent div from firing the blur event if any one of its children receive focus?

<div tabindex="-1" onblur="alert('outer')">
    <input type="text" value="Soup" />
</div>

I just wrote the code without a compiler, so I am not sure if that even works, but with that, hopefully you get the idea.

I'm using Knockout.js to update the GUI on the fly, but that shouldn't affect this answer I wouldn't have thought.


Solution

  • I've had to tackle this problem before. I am not sure if it is the best solution, but it is what I ended up using.

    Since the click event fires after the blur, there is no (cross-browser, reliable) way to tell what element is gaining focus.

    Mousedown, however, fires before blur. This means that you can set some flag in the mousedown of your children elements, and interrogate that flag in the blur of your parent.

    Working example: http://jsfiddle.net/L5Cts/

    Note that you will also have to handle keydown (and check for tab/shift-tab) if you want to also catch blurs caused by the keyboard.