Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onblur vs onclick timing

There is a textarea element which converts itself into a div when onblur event happens on that same textarea. There is also a button which has its onclick property set to function f.

If one is writing in the textarea and then clicks on a button, f is fired, but also onblur event handler is triggered. Is there some order rules in this case, or the two handler functions may fire in random order?

like image 588
lavokad Avatar asked Apr 04 '14 15:04

lavokad


People also ask

Does Onblur fires before onClick?

If you try to click the button while you are writing, it won't display the 'Click' alert, as onBlur prevents onClick to execute. A solution could be to use onMouseDown instead of onClick . That works because the onMouseDown event has a higher priority than the onBlur event.

What is the difference between onClick and onMouseDown?

You would use onMouseDown if you want to preventDefault as soon as the user clicks on a button. This is preferred in a texteditor where you want to keep the focus on the input while clicking on buttons that change the styles of the text.

What is the difference between Onblur and Onfocus?

Definition and Usage Tip: The onblur event is the opposite of the onfocus event. Tip: The onblur event is similar to the onfocusout event. The main difference is that the onblur event does not bubble. Therefore, if you want to find out whether an element or its child loses focus, you could use the onfocusout event.

When would an Onblur event occurs?

The HTML DOM onblur event occurs when an object loses focus. The onblur event is the opposite of the onfocus event. The onblur event is mostly used with form validation code (e.g. when the user leaves a form field).


1 Answers

I created a jsfiddle here: http://jsfiddle.net/z5SEp/

The events for latest Chrome seem to be:

mousedown
blur
mouseup
click 

Although I could not find any documentation to rely on, it would make sense to me that blur is fired after mousedown, but before mouseup. Mousedown causes blur, but you could leave your mouse button down for an extended period of time and still cause a blur.

The order of click events will always be 1. mousedown 2. mouseup 3. click. The blur makes sense to be after mousedown but before mouseup.


More things to keep in mind

If you trigger the button click like this: $('button').trigger('click');, then the blur event will not fire, and focus will remain on the textarea.

like image 65
Joe Frambach Avatar answered Oct 05 '22 23:10

Joe Frambach