Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

290
Visualizações
How can I run code in the onload event in a file and in a script tag

I wish to add code to a click event in a file and a script tag. But they seem to conflict. How can I achieve this?

javascript:

 window.onload = function()
 {
     document.getElementById("button3").addEventListener("click", respond3);
 }

 function respond3(e)
 {
     alert("Way to go!!");
 }

html:

<head>
    <title>Second Javascript</title>

    <script src="Second.js"></script>
    <script>
        window.onload = function()
        {
            document.getElementById("button2").addEventListener("click", respond);
        }

        function respond(e)
        {
            alert("getting better");
        }
    </script>

</head>

<body>
    <h1>The quick brown fox jumps over the lazy dogs</h1>
    <button onclick='alert("bad practice");'>Inline</button>
    <button id='button2'>Script tag</button>
    <button id='button3'>Separate file</button>
</body>

Per Quentin's suggestion I changed the script tag to this:

<script>
    window.addEventListener('load', AddClick2)

    function AddClick2()
    {
        document.getElementById("button2").addEventListener("click", respond);
    }

    function respond(e)
    {
        alert("getting better");
    }

</script>
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The on* properties can only have one function assigned to them. It's not so much a conflict as you are simply overwriting the first onload function with the second.

While you could do something along the lines of checking to see if there is already a function there, then copying it to a new variable, then calling it from the new variable inside your new onload function … that gets messy.

Use addEventListener instead.

window.addEventListener('load', a_function);
window.addEventListener('load', a_different_function);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda