Home > OS >  ReferenceError: Can't find variable: e - simple e.preventDefault() function
ReferenceError: Can't find variable: e - simple e.preventDefault() function

Time:02-27

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?

CodePudding user response:

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 >
  <a href="http://google.com"></a>
</div>

CodePudding user response:

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');
})

CodePudding user response:

You don't need to pass e as a parameter to your onclick function. The event object is captured automatically. You also don't need the parenthesis when you call the function in your event listener. Doing so will call it when the page loads as well as when the event is triggered, which you probably don't want.

element.onclick(handleClick)

Function handleClick(e) {
  e.preventDefault;
  //awesome code goes here
}

CodePudding user response:

//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>

CodePudding user response:

Instead of using e in the onclick property, use event.

<div class='test'>
  <a onclick='testToggle(event)'></a>
</div>

<script>
  const el = document.querySelector('.test');

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

  • Related