Home > OS >  Fire clicks inside of setInterval only one time with jQuery or Javascript
Fire clicks inside of setInterval only one time with jQuery or Javascript

Time:12-24

A website shows a cookie consent after arround 1-2 seconds, if a user has not give a consent. That means, the consent is not in the source directly but in the dom after 1-2 seconds.

I have to detect if a user clicks on a button inside of the consent div. If I use the document ready function, the click is not detected. I have to use setInterval because setTimeout doesn't work. The reason is that another window has to be opened in the Consent and therefore I cannot use a fixed time as with a timeout.

The Consent div is sourrended by a div with the class name "cmp-consent". I check the dom with setInterval every 1800ms for that div. If the div is not existend after 1800ms the user has already given the consent and I clear the setInterval.

BUT:

If the div exists, it waits until the user clicks on the second button in the consent header. When this click is made, another click is made and the window is closed. This is working very well.

The problem is, if a user does not click this button (consent-header button: eq (1)) immediately, the setInterval will of course continue to run. You can see the counter in front of the console.log is increasing. If a user then clicks the button, the subsequent clicks are carried out as often as there is a setInverval. This takes too long if a user waits, for example, longer then a minute. The question is, how do you manage that an action is only carried out once in a setInterval.

Here is my script:

var userConsent = window.setInterval(function() {
if ($(".cmp-consent")[0]){

console.log('consent exists');  

    $( ".consent-header button:eq(1)" ).click(function(){   

        console.log('User clicked the button');
        $(".primary button").click();
        $(".close-icon").click();           

        window.clearInterval(userConsent);
    });


} else {

console.log('consent given, remove interval');
window.clearInterval(userConsent);

} 

}, 1800); 

CodePudding user response:

Here is a working example of @cloned's suggustion.

document.addEventListener("click", function(e) {
    for (var target=e.target; target && target!=this; target=target.parentNode) {
    // loop parent nodes from the target to the delegation node
        if (target.matches('.consent-header')) {
            handler.call(target, e);
            break;
        }
    }
}, false);

function handler() {
  console.log('do stuff');
}
<div >
<button>I agree</button>  
</div>

  • Related