E
E
Eugene Wolf2018-12-01 23:57:23
JavaScript
Eugene Wolf, 2018-12-01 23:57:23

How to emulate a click on an element after it has been rendered?

Good day dear!
Can you please tell me how to correctly "call" click () on an element after it has been rendered?
The essence of the problem, and my attempts to solve it:

methods: {
    clickFunction() { //Функция которая "эмулирует" событие "click"
        document.querySelector('#myInput').click(); //Вот так - всё работает, проблема только в том, что в этот момент времени элемент ещё не успел отрендерится, по этому "кликать некуда"

        //Порывшись в документации VueJS нашел вот такое "решение":
        this.$nextTick(function() {
            document.querySelector('#myInput').click(); //Не работает
        }

        //Нашел некий "костыль" призванный исправить сие
        setTimeout(function () {
            document.querySelector('#myInput').click(); //Но... он тоже не работает
        }, 0); //И если добавить времени, например 500 или 1000мс - он тоже не работает
    }
}

Is there any way to deal with this, and if so, how?
PS I generally understand where the problem "legs grow" from and have a general understanding on the topic "why it is so" ... I do not understand how to solve this correctly and whether it can be solved at all, correctly. I think the task is rather banal, "wait until the element is rendered and do something with it."
The element - represented in the example - is a FileInput (you need to click on it to bring up a file selection dialog), level options "replace it with something else" or "create a million inputs in advance and then use them", etc. options - disappear immediately.
I this.$refsalso tried it, the effect is similar (does not work).
UPD. An alternative, for ease of understanding:
methods: {
    async clickFunction() {
        await this.$nextTick();
        document.querySelector('#myInput').click(); //Так работать не будет, но если бы функция не была асинхронной - всё бы работало исправно
    }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
Philip Gaponenko, 2018-12-02
@filgaponenko

You can try using the mounted component's lifecycle hook .
To generate an event, you need to use the dispatchEvent method in which to pass an event of the desired type created using the constructor .
Example

0
0xD34F, 2018-12-02
@0xD34F

The element - presented in the example - is a FileInput (you need to click on it to bring up the file selection dialog)

No, you won't succeed. This dialog can only be opened as a result of real user actions (and not all of them: clicking, pressing a key - okay; scrolling, mouse movement, calling the context menu - no), and not their imitation. At least in Chrome. You can simulate in Firefox.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question