12

I am creating a responsive menu: Codepen Demo

To avoid the page to be reloaded when I click a link I have:

$('nav.menu a[href="#"]').click(function () {
  $(this).preventDefault();
});

But this does not seem to work. When I click a button the menu disappears.

Does anyone knows what I am be doing wrong?

Arturs
  • 1,258
  • 5
  • 21
  • 28
Miguel Moura
  • 36,732
  • 85
  • 259
  • 481

7 Answers7

31

It's not the element that need a .preventDefault(), its the click event.

Try this:

$('nav.menu a').click(function (event) {
  event.preventDefault();
  // or use return false;
});

I don't recommend to use the href as selector though, better to give it an id or name.

From MDN, about .preventDefault():
Cancels the event if it is cancelable, without stopping further propagation of the event.


You can read more here:


There is a CSS way, using pointer-events.

So by using in the CSS pointer-events: none; all click will be ignored. This is a "recent" alternative and suported in IE11+, Firefox 3.6+, Chrome 2.0+, Safari 4+.

Example

Sergio
  • 28,539
  • 11
  • 85
  • 132
7

Here is very easy way to do it inside html.

<a class="font-weight-bold" href="javascript:void(0);"> Click Here </a>
Muhammad Ahsan
  • 608
  • 15
  • 28
5

Just return false.

$('nav.menu a[href="#"]').click(function () {
  return false
});
slinky2000
  • 2,663
  • 1
  • 15
  • 12
2

Use like that:

$('nav.menu a[href="#"]').click(function (event) {
  event.preventDefault();
});
Murat Çorlu
  • 8,207
  • 5
  • 53
  • 78
0

Try this:

$('.menu a').click(function(e){
   e.preventDefault(); // stop the normal href from reloading the page.
});

Working codepen example: http://codepen.io/anon/pen/cynEg

You did not have a reference to the jquery library included. Also the 'enquire' function is now throwing an error but preventDefault is working.

Edit I have commented out the second function.

lharby
  • 3,057
  • 5
  • 24
  • 56
0
$('nav.menu a[href="#"]').click(function (e) {
   e.preventDefault();
});
kazimt9
  • 563
  • 5
  • 11
0

And an inline option without jQuery:

<a href="javascript:function f(e){e.preventDefault();}">Link</a>

And don't forget that with this you have already used the "f" name for a function, so don't name other function like this.

adkl
  • 634
  • 7
  • 17