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

121
Views
addEventListener in onclick firing onload

I'm currently trying to get a with an onclick function to fire only when clicked. But I'm noticing after it's clicked and then on page load, the function is firing again.

Once I click 'Previous', the page goes to '/test1' for a second, then instantly loads '/test'. Am I not using this eventListener correctly?

Note: '/test1' and '/test2' are in one react project and '/test' is in another. I cannot use history.push for this scenario.

Header.js

<div id="header-link">
    <strong id="header-copy"></strong>
</div>

Entry.js

function getLink(currentPage, history) {
    if(currentPage.name === 'test1') {
        document.getElementById("header-link").addEventListener("click", function(e){
            e.preventDefault();
            window.location.pathname = '/test'
        });
        document.getElementById("header-copy").innerHTML = 'Back';
    }
    if (currentPage.name === 'test2') {
        document.getElementById("header-link").addEventListener("click", function(){ 
        history.push('/test1') 
        });
        document.getElementById("header-copy").innerHTML = 'Previous';
    }
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You don't need to use addEventListener when onClick is enough.

import { useHistory } from "react-router-dom";

const Header = () => {
  let history = useHistory();
  return (
    <div
      onClick={() => {
        if (window.location.href.endsWith("/test")) {
          history.push("/");
        } else {
          window.location.pathname = "/test";
          //history.push("/test");
        }
      }}
    >
      Click me
    </div>
  );
};

But if you insists on using addEventListener you need to remove them.

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!