Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

287
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!