Add onclick or listener to a non-existent element

Asked

Viewed 185 times

1

I have an external widget that has a form, but I can’t change the way it works (because it’s proprietary). However I need to know when the user clicked on it to auto fill some fields like name and email, which are saved in my system session.

I was thinking of adding elemento.addEventListener('click', inserirDados);. But as it is asynchronous, I don’t know when it will finish being loaded. How can I do that? I don’t know if it’s important, but both my system and widget use pure javascript only.

The widget is inserted on the page with:

(function() {
    //criação do <script>
    //configuração
    //inserção do script na página
})();

From now on, thank you!

  • What is your element where the widget is inserted?

  • At the end of the body, with global scope, to be available throughout the system.

2 answers

1

You have to delegate that event to another element that already exists on the page. How do you say it is inserted into body that’s exactly what you should use. Then you have to check if the click was inside that element or class:

document.body.addEventListener('click', event => {
    const elemento = document.querySelector('#id-do-widget');
    if (event.target.contains(elemento)) return;
    inserirDados(event);
});

1


How do you identify the widget? Why an ID? Why be inside an element? If your widget is contained within an element, such as a div, you can add the event to the element, any click on it, or an element within it will trigger the click event.

const meuWidget = document.getElementById('meuWidget');
    
//Widget é carregado assincronamente    
setTimeout(() => {
    meuWidget.innerHTML = `
    <label>Nome</label>
    <input name="nome"/>
    <label>CPF</label>
    <input name="cpf"/>
    <label>Contato</label>
    <input name="contato"/>`;
}, 3000);


meuWidget.addEventListener('click', e => {
    switch(e.target.name) {
        case "nome":
           console.log('Clicou no nome');
           break;
        case "cpf":
           console.log('Clicou no cpf');
           break;
        case "contato":
           console.log('Clicou no contato');
           break;
    }
})
<div id="meuWidget">

</div>

  • The call is not inside a div, as the widget loads itself with <script></script> that loads the JS mentioned in the question. From what I understood, just put the <script> inside a div already solves?

  • No, where the script that loads your widget is not important, what matters is where your widget is rendered. What is the parent element of the widget? Add the eventListener in that father.

  • Even though it wasn’t the choice considering Occam’s razor, his answer helped me better understand the context besides answering the question. Thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.