Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
230 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...