爱国者
爱国者

Reputation: 4338

unable to click each other repeatedly

Hard to explain in human language, just show the code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang='zh-CN' xml:lang='zh-CN' xmlns='http://www.w3.org/1999/xhtml'>
<head>
    <script type="text/javascript">
        function call_f1(){
            document.getElementById('f1_div').click();

            // document.getElementById('f1_div').click();
        }

        function f1(){
            console.log('f1 '+new Date());               
            document.getElementById('btn_1').click();                
        }

    </script>
</head>
<body>
    <input id="btn_1" type="button" onclick="call_f1()" value="callf1"></input>
    <div id="f1_div"  onclick="f1()" style="background: red; width: 35px; height: 35px;">
    </div>
</body>

When you click the button using your mouse, you get a single output on the console. Why?? Doesn't f1 function invoke repeatly?

Upvotes: 0

Views: 91

Answers (3)

jacksky007
jacksky007

Reputation: 21

http://www.w3.org/TR/html5/dom.html#run-synthetic-click-activation-steps So, add timeout to the two functions call. As below.

    var timeout = 0; // change this to whatever suites for you
    function call_f1(){
        setTimeout(function(){
            document.getElementById('f1_div').click();
        }, timeout);

        // document.getElementById('f1_div').click();
    }

    function f1(){
        console.log('f1 '+new Date());               
        setTimeout(function() {
            document.getElementById('btn_1').click();
        }, timeout);                
    }

Upvotes: 2

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123453

Why?? Doesn't f1 function invoke repeatly?

No. .click() and the synthetic click activation it starts won't do anything when there's already an active 'click' event for the element.

  1. If the element's click in progress flag is set to true, then abort these steps.

  2. Set the click in progress flag on the element to true.

If you want it to be continuous with .click(), you'll have to allow the previous event to finish first. Probably with the use of a timer:

function f1(){
    console.log('f1 '+new Date());

    setTimeout(function () {
        document.getElementById('btn_1').click();
    }, 1);
}

Upvotes: 1

Daniele Vrut
Daniele Vrut

Reputation: 2873

try with:

   function call_f1(){
        document.getElementById('f1_div').onclick();

        // document.getElementById('f1_div').onclick();
    }

    function f1(){
        console.log('f1 '+new Date());               
        document.getElementById('btn_1').onclick();                
    }

This one is working for me: http://jsfiddle.net/djhell/rG782/

Upvotes: 1

Related Questions