Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a div on a page that shows some info 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, 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 wouldn't let me, need 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 what I then decided to do is create an 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 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 effect this answer I wouldn't have thought.

like image 485
Thwaitesy Avatar asked Aug 23 '12 13:08

Thwaitesy


People also ask

How can blurred events be prevented?

If you want to prevent the blur event from being fired, you have to do so when you are inside the mousedown event, you can do so by invoking the method preventDefault() on the event. Click the checkbox, focus input & then click the button, the textfield never loses focus now.

What is the use of focus and blur event?

The blur event fires when an element has lost focus. The main difference between this event and focusout is that focusout bubbles while blur does not. The opposite of blur is focus . This event is not cancelable and does not bubble.

Which event is triggered when a field loses focus?

The onblur event occurs when an object loses focus. The onblur event is most often used with form validation code (e.g. when the user leaves a form field).

What triggers blur?

Definition and Usage. The blur event occurs when an element loses focus.


1 Answers

I faced the same issue. This what worked for me.

 handleBlur(event) {     // if the blur was because of outside focus     // currentTarget is the parent element, relatedTarget is the clicked element     if (!event.currentTarget.contains(event.relatedTarget)) {         .....     } } 

Enjoy :)

like image 112
Yahel Yechieli Avatar answered Sep 23 '22 03:09

Yahel Yechieli