How to trigger event in JavaScript?

前端 未结 18 1866
情深已故
情深已故 2020-11-21 04:48

I have attached an event to a text box using addEventListener. It works fine. My problem arose when I wanted to trigger the event programmatically from another

18条回答
  •  清歌不尽
    2020-11-21 05:07

    The accepted answer didn’t work for me, none of the createEvent ones did.

    What worked for me in the end was:

    targetElement.dispatchEvent(
        new MouseEvent('click', {
            bubbles: true,
            cancelable: true,
            view: window,
    }));
    

    Here’s a snippet:

    const clickBtn = document.querySelector('.clickme');
    const viaBtn = document.querySelector('.viame');
    
    viaBtn.addEventListener('click', function(event) {
        clickBtn.dispatchEvent(
            new MouseEvent('click', {
                bubbles: true,
                cancelable: true,
                view: window,
        }));
    });
    
    clickBtn.addEventListener('click', function(event) {
        console.warn(`I was accessed via the other button! A ${event.type} occurred!`);
    });
    
    
    

    From reading: https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent

提交回复
热议问题