mattbtay
mattbtay

Reputation: 135

e.preventDefault - e is not defined

So I have this JS and when i run the code i get "e is not defined" - What am I missing?

$('ul.result-filters > li a').click(toggleFilters());

function toggleFilters(e) {
   e.preventDefault();
   //do more stuff
}

Upvotes: 1

Views: 4407

Answers (5)

Adil
Adil

Reputation: 148110

You are calling function instead of passing handler name to click. Remove the parenthesis from toggleFilters()

Change

$('ul.result-filters > li a').click(toggleFilters());

To

$('ul.result-filters > li a').click(toggleFilters);

Upvotes: 1

Sridhar Narasimhan
Sridhar Narasimhan

Reputation: 2653

You need to use the function name instead of function call toggleFilters().

$('ul.result-filters > li a').on('click', toggleFilters);

function toggleFilters(e) {
 e.preventDefault();
//do more stuff
}

Thanks

Upvotes: 0

crowebird
crowebird

Reputation: 2586

Can always do e = e || window.event to ensure you have the event.

Upvotes: 1

adeneo
adeneo

Reputation: 318182

$('ul.result-filters > li a').on('click', toggleFilters);

function toggleFilters(e) {
   e.preventDefault();
   //do more stuff
}

When adding the parenthesis after the function it's executed immediately and the results are passed back. To just reference the function and call it on click, drop the parenthesis.

This would also make the event available to the toggleFilters function!

Upvotes: 4

Denys Séguret
Denys Séguret

Reputation: 382132

Use this :

$('ul.result-filters > li a').click(toggleFilters);

You were passing the result of toggleFilters() instead of passing the function itself.

Upvotes: 9

Related Questions