• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

215
Views
ReferenceError: Can't find variable: e - simple e.preventDefault() function

I'm surprised this error is occurring but I do not actually know how to fix it. To summarise, I'm getting this error:

ReferenceError: Can't find variable: e 

But the event object should be found, as it is being passed into the function... So why is it not being found? I assume I'm doing something pretty daft here.

a {
  font-size: 2em;
}
a:after {
  content: 'a';
}
div.show a:after {
  content: 'b';
  color: blue;
}
<div class='test'>
  <a onclick='testToggle(e)'></a>
</div>
<script>
  const el = document.querySelector('.test');

  const testToggle = (e) => {
    e.preventDefault();
    el.classList.toggle('show');
  }
</script>

I can of course just remove the preventDefault and e variable, but I need the preventDefault behaviour to stop the dom from scrolling after clicking the link.

Can someone advise where I'm going wrong here?

about 3 years ago · Juan Pablo Isaza
3 answers
Answer question

0

I would avoid inline JS listeners and use addEventListener instead.

const el = document.querySelector('.test');
el.addEventListener('click', testToggle, false);

function testToggle(e) {
  e.preventDefault();
  el.classList.toggle('show');
}
a { font-size: 2em; }
a:hover { cursor: pointer; }
a:after { content: 'a'; }
div.show a:after { content: 'b'; color: blue; }
<div class="test">
  <a href="http://google.com"></a>
</div>

about 3 years ago · Juan Pablo Isaza Report

0

do it like this :

HTML

<div class='test'>
  <a id="toggle">test</a>
</div>

JS

const el = document.querySelector('.test');
const toggle = document.getElementById("toggle")
toggle.addEventListener("click", (e) => {
  e.preventDefault();
  el.classList.toggle('show');
})
about 3 years ago · Juan Pablo Isaza Report

0

//html 
<div class='test'>
    <a></a>
</div>
//js you can use event listener to have the click event 
<script>
    const el = document.querySelector('.test');
    const link= document.querySelector('.test a');

    link.addEventListener('click', (event) => {
        event.preventDefault()
        el.classList.toggle('show')
    });
</script>
about 3 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 Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error