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