Create widget with "onclick()"

Asked

Viewed 371 times

1

I need to create an element with Javascript that, when clicked, call a function.

Is there any event I can add to my code for that ? It would be equal to onclick() that we put inside an html tag.

Follows the code

let inputExc = document.createElement('i') //cria
inputExc.className = 'fas fa-trash-alt ml-2' //define class
inputExc.title = 'Excluir' //define title
inputExc.id = 'iExcluir' //define id
  • 1

    How about the onclick?

  • The onclick worked, thanks. But I had to call the function at the time I do the assignment, so: "inputExc.onclick = Function removerItem(){}"

3 answers

4


You must use your own onclick.

//método do evento
let clickLixeira = function () { 
  console.log('Clicou na lixeira');
}

let inputExc = document.createElement('i') //cria
inputExc.className = 'fas fa-trash-alt ml-2' //define class
inputExc.title = 'Excluir' //define title
inputExc.id = 'iExcluir' //define id

// bind do evento com o método
inputExc.onclick = clickLixeira;

//adicionando o elemento na tela
document.getElementById("container").appendChild(inputExc);
@import 'https://use.fontawesome.com/releases/v5.7.0/css/all.css';
<div id="container">
</div>

  • That way it worked without problems, thank you very much! But I think the code is kind of "messy" that way, there’s no way instead of me opening keys, ?

  • Of course, you just need to pay attention to the scope of where you will declare this method, see my edition.

  • Beauty Leandro, thank you so much for the suggestions !

2

Use the nomeDoElemento.click().

inputExc.click(nomeDaFunção) or can create a function:

inputExc.click(function(){
})
  • Test this method and the function is executed as soon as this element is created, not when I click on it.

2

You can use the addeventlistener

inputExc.addEventListener("click", function(){
});

Browser other questions tagged

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