Jett
Jett

Reputation: 880

Treat Single Click and Double Click as same

I would like to be able to execute foo() once regardless of whether I click on the button once or twice.

<span> (click)="foo()" </span>

foo() {
    console.log("You've clicked on foo");
}

I've tried using this stackoverflow answer but clicking on it twice still results in multiple console.logs. How would be able to only run this function once?

Note: Not really looking for triple/quadruple clicks (only single/double)

Upvotes: 3

Views: 333

Answers (1)

StepUp
StepUp

Reputation: 38174

Try to use setTimeout, clearTimeout and handle user clicks:

<span 
    (click)="func1()" 
    (dblclick)="func2()">
    Hello
</span>

TypeScript:

timer = 0;
delay = 200;
prevent = false;

func1(){
    this.timer = setTimeout(() => {
        if (!this.prevent) {
            this.sayHello();
        } 
        this.prevent = false;
    }, this.delay);
}

func2(){
    clearTimeout(this.timer);
    this.prevent = true;
    this.sayHello();
}

sayHello(){
    console.log('Hello, world!:)');
}

The work stackblitz example

Upvotes: 1

Related Questions