Is there any way to write a function on the screen other than by onclick? [closed]

3
Hello, the only way I can call a javascript function in html is by onclick, but my html is not a button to click, I would like to know if there is another way to display a function when it is called.

ex: onload -> para quando a tela carregar
onclick -> quando clicarem no elemento

Are there any that just show?

    
asked by anonymous 13.10.2017 / 20:25

3 answers

3
function fazerAlgo()
{
  //código aqui
}
// em alguma parte do seu código mais tarde...
fazerAlgo();

No HTML:

<script src="minhafuncao.js"></script>
<div id="">Em alguma parte do seu html</div>
<script>fazerAlgo();</script>
    
13.10.2017 / 20:38
3

In your own question is one of the alternatives: no onload .

If you do not want to call the function through a direct action user (eg click Explicit , either during page loading, simply calling the function after the function code:

<script>
function minhaFuncao(){
...
}
minhaFuncao();
</script>

Or after page load:

<script>
function minhaFuncao(){
...
}
window.onload = minhaFuncao;
</script>
    
13.10.2017 / 20:54
1

There are several Listener's that can be used, some examples and ways of application with pure JavaScript:

document.addEventListener('click', suaFuncao(), true); // No Clique
document.addEventListener('load', suaFuncao(), true); // No load
document.addEventListener('resize', suaFuncao(), true); // No Resize

and to apply them let's suppose, in the click:

const btn = document.querySelector('classe ou id do seu botao');
btn.addEventListener('click', suaFuncao(), true);
    
13.10.2017 / 20:52