Home > Net >  Is it possible to hold down element.click for a certain amount of time?
Is it possible to hold down element.click for a certain amount of time?

Time:09-04

Context: Creating a keyboard element in svelte, i want to emulate a user click to show the animation, but btn.click() is to short to show the transition.

Using btn.click() does fire a click element, but it's too short for the user to notice.

Ive tried using btn.focus() and btn.blur() but it doesn't play the animation, it only causes a border to show up.

Is there a way for me to emulate a click for X amount of time?
This is my code (per key)

<script lang=ts>
    import { addLetter, enter, removeLetter, onKeyPress } from "./state";
    export let key: string;
    let btn: HTMLButtonElement;
    function handle(e: MouseEvent) {
        if(!e.isTrusted) return
        if(key === "DELETE") {
            removeLetter(false)
        } else if(key === "ENTER") {
            enter(false)
        } else {
            addLetter(key, false)
        }
    }

    onKeyPress((k, kb) => {
        if(!(k === key) || !kb) return
        btn.click() //! LOOK HERE
    })
</script>

<button  bind:this={btn} on:click={handle}>{key}</button>

CodePudding user response:

You could run an animation rather than using transitions, e.g.

<script>
    let button;
    function onKeyDown(e) {
        if (e.key == 'f') {
            animate();
        }
    }
    
    function animate() {
        button.animate(
            [{ background: 'red' }],
            { duration: 200, direction: 'alternate', iterations: 2 },
        )
    }
</script>

<svelte:window on:keydown={onKeyDown}/>

<button bind:this={button} on:click={animate}>F</button>

Single Key
Full Keyboard

CodePudding user response:

What you are looking for is mousedown and mouseup events

<script lang=ts>
    import { addLetter, enter, removeLetter, onKeyPress } from "./state";
    export let key: string;
    let btn: HTMLButtonElement;
    let mousedownTime: Date;
    function handle(e: MouseEvent) {
        if(!e.isTrusted) return
        if(key === "DELETE") {
            removeLetter(false)
        } else if(key === "ENTER") {
            enter(false)
        } else {
            addLetter(key, false)
        }
    }

    function mouseDown() => {
       mousedownTime = new Date().getTime();
    }
    function mouseUp() {
        const mouseupTime = new Date().getTime(),
        timeDifference = mouseupTime - mousedownTime;
        alert(`Button held down for ${timeDifference}ms`);
    }

    onKeyPress((k, kb) => {
        if(!(k === key) || !kb) return
        btn.click() //! LOOK HERE
    })
</script>

<button  bind:this={btn} on:mousedown={mouseDown} on:mouseup={mouseup}></button>
  • Related