LoginSignup
51
28

More than 5 years have passed since last update.

onclick()とonblur()の順序

Last updated at Posted at 2016-05-14

最初以下の例を見てみます。

<input id="Text1" type="text" onblur="alert('onblur')"/>
<input id="Button1" type="button" value="button" onclick="alert('onclick')"  />

デモ:https://jsfiddle.net/thanh1992/8eej3m91/
テキストを入力した後、ボタンをクリックしてみると、onblurイベントは発動しますが、onclickイベントは発動しません。

1.onclickイベントを動かないことの修正

onclickイベントの代わりに、onmousedownイベントを使います。

<input id="Text1" type="text" onblur="alert('onblur')"/>
<input id="Button1" type="button" value="button" onmousedown="alert('onclick')"  />

デモ:https://jsfiddle.net/thanh1992/z0cmuoeq/
結果は、onmousedownイベントが発動した後、onblurイベントが発動します。1

2.イベントの順序

以下はイベントのタイミング(早->遅)

 mousedown
 blur
 mouseup
 click 

コード:

<input id="Text1" type="text" onblur="console.log('blur');"/>
<input id="Button1" type="button" value="button" onclick="console.log('click');"  onmousedown="console.log('mousedown');" onmouseup="console.log('mouseup');"/>

デモ:https://jsfiddle.net/thanh1992/uep6n2x9/

3.結論

イベントのタイミングが違いますから、コードがうまく動くように、イベントの順序に注意してください。


  1. Firefoxの場合。Google Chromeの場合はonmousedownのみ発動します。 

51
28
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
51
28