0

I have a question regarding the onBlur DOM event. I was wondering if I set an onBlur event handler on a div. Does it fire if I focus on a child element inside of that div. I want to submit an ajax request to an MVC controller when a div containing all the necessary input elements handles the onBlur event.

Also this would be saving a list of entities related to the main model (in a partial view) which may either be an edit or a create. I would test this out myself, but I still need to set up the controller action and move my markup to a partial view.

Luke Weaver
  • 271
  • 1
  • 9
  • It's such a basic thing to try this and find out. – Reinstate Monica Cellio Jan 29 '18 at 18:31
  • Events bubble to parents unless they are stopped with `stopPropagation` (stop bubbling) or `stopImmediatePropagation` (stop bubbling + don't execute any other handlers bound to the element). – Ravenous Jan 29 '18 at 18:32
  • Div elements do not trigger a blur event. Only elements that can be focused will trigger that event. – Reinstate Monica Cellio Jan 29 '18 at 20:16
  • JQuery allows you to add a handler on blur for just about anything nowadays (at least on the more recent browsers). Think of it like when you're on youtube & hit the space bar to pause. If you aren't focused on that element where the video plays, it will just scroll down a bunch. – Luke Weaver Jan 29 '18 at 22:05
  • I will get onto testing this myself now, I was wanting to make sure what I was planning was do-able before I commit too much to something that wouldn't work. I'm almost to the point where I can test this on the view so I'll figure it out – Luke Weaver Jan 29 '18 at 22:49

1 Answers1

0

Yes, it will fire on the container event, because of event bubbling, unless a listener on an element calls event.stopPropagation() to prevent bubbling further.

But this event doesn't mean you left the DIV. E.g. if you have HTML like:

<div>
    <input name="in1" type="text">
    <input name="in2" type="text">
</div>

If you go from in1 to in2 a blur event will be triggered on in1. This event will bubble out to the DIV as well.

If you want to detect a click outside the DIV, see How do I detect a click outside an element?

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Thank you, that was helpful with my planning. I was also trying to figure out if you clicked/focused on an text box inside of a parent div. Would that parent div dispatch the Blur event still? Or would it still technically be focused on since the user would be focused on a child element inside of the parent. My goal is to send an ajax call whenever the user is done inputting data and clicks outside of the form/parent div. Saving it without the need of a button as a requirement for a project. – Luke Weaver Jan 29 '18 at 22:46
  • Any time you change the focused element, a `blur` event is triggered. It doesn't matter what the new focused element is. – Barmar Jan 29 '18 at 22:55