Clodoaldo Neto
Clodoaldo Neto

Reputation: 125244

Events order not as expected

I have an image animation code set so it happens in certain page update events. It works as expected. As the update can fail and I don't want the animation to play forever I want that it be stopped whenever the user clicks anywhere or press a key. For the key press event it is working and is this:

<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        function RefreshImg() {
            var src = $('#ocupado').attr('src');
            $('#ocupado').attr('src', src);
        }

        function processando() {
            $processando = $('#processando');
            $processando.css('z-index', '100').fadeTo('fast', 0.5);
            var left = Math.floor(($processando.outerWidth() - 32) / 2);
            var top = Math.floor(($processando.outerHeight() - 32) / 2);
            $('#ocupado').css('left', left).css('top', top);
            setTimeout(RefreshImg, 50);
            $(document).on('keypress', (function () {
                $processando.fadeOut('fast').css('z-index', '-100');
                $(this).off('keypress');
            }));
        }
    </script>
</head>
<body>
    <div id="processando" style="border:0;position:fixed;display:none;z-index:-100;width:100%;height:100%;background:black;top:0px;left:0px;">
    <img id="ocupado" src="http://upload.wikimedia.org/wikipedia/commons/d/de/Ajax-loader.gif" width="32" height="32" style="position:relative;" border="0" alt="imagem de espera" />
    </div>
    <select id="mySelect"><option>1</option><option>2</option></select>
    <script type="text/javascript">
        $('#mySelect').change(processando);
    </script>
</body>
</html>

The problem is when I change the code to include the click event:

$(document).on('keypress click', (function () {
    $processando.fadeOut('fast').css('z-index', '-100');
    $(this).off('keypress click');
}));

Now the animation starts and stops as soon as the user changes the select option. It is as if the click event happens after the change event. How to make the animation to stop only at first click after the select change?

Upvotes: 0

Views: 94

Answers (1)

castillo.io
castillo.io

Reputation: 942

I think the jQuery blur() function can do what you want. See the updated code here:

http://jsfiddle.net/j8fJZ/1/

As you can see, you can also trigger the blur on keydown.

Upvotes: 3

Related Questions