すたらSample

『mousedown > blur > click』の検証 (jQuery)

2011/12/08

失敗:blurが優先され、clickが失敗する

テキストボックスが広がった状態で送信ボタンをクリックすると、
テキストボックスの収縮が優先されて、それにつられて送信ボタンの
位置もズレて、クリックに失敗してしまいます。


ソース全文
<!doctype html>
<html lang="ja">
    <head>
        <meta charset="UTF-8">
        <title></title>
        <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
        <script type="text/javascript">
            jQuery(document).ready(function($){
                $('#area1')
                    .focus(function(){ $(this).attr('rows', 8) })
                    .blur (function(){ $(this).attr('rows', 2) });
                $('#btn1').click(function(){
                    alert($('#area1').val());
                });
            });
        </script>
    </head>
    <body>
        <textarea cols="40" id="area1">フォーカスされると、
領域が広がります。</textarea><br>
        <input type="button" id="btn1" value="送信(仮)">
    </body>
</html>

成功:mousedownが優先され、その後にblurが実行される

blurよりも優先されるmousedownをボタンに追加したことで、
送信処理の後にテキストボックスが収縮するという、
望みどおりの結果になりました。


ソース全文
        <script type="text/javascript">
            jQuery(document).ready(function($){
                $('#area2')
                    .focus(function(){ $(this).attr('rows', 8) })
                    .blur (function(){ $(this).attr('rows', 2) });
                $('#btn2')
                    //Enterキーでボタンが押された場合のために、必要
                    .click(alertText)

                    //blurよりも順番が優先される
                    .mousedown(alertText);
            });
            function alertText(){ alert($('#area2').val()) }
        </script>