Disallow link to reload page

I am creating a responsive menu: Codepen Demo

To avoid reloading the page when I click the link, I:

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

But this does not seem to work. When I press the button, the menu disappears.

Does anyone know what I'm doing wrong?

+4
source share
7 answers

This is not an element that needs .preventDefault() , its event click.

Try the following:

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

I do not recommend using href as a selector, but it's better to give it id or name .

From MDN, about.preventDefault ():
Cancels an event if it is canceled without stopping the further distribution of the event.


You can read here:


There is a CSS way using pointer events .

Thus, using CSS pointer-events: none; , all clicks will be ignored. This is a "recent" alternative and is supported in IE11 +, Firefox 3.6+, Chrome 2.0+, Safari 4+.

Example

+22
source

Just return false.

 $('nav.menu a[href="#"]').click(function () { return false }); 
+5
source

Use this:

 $('nav.menu a[href="#"]').click(function (event) { event.preventDefault(); }); 
+2
source
 $('nav.menu a[href="#"]').click(function (e) { e.preventDefault(); }); 
0
source

And the built-in option without jQuery:

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

And don't forget that with this you already used the function name f for the function, so don't call another function like this.

0
source

Here's a very easy way to do this inside html.

 <a class="font-weight-bold" href="javascript:void(0);"> Click Here </a> 
0
source

Try the following:

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

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

You did not have a link to the jquery library. Also, the "request" function now throws an error, but preventDefault works.

Edit I commented on the second function.

-one
source

Source: https://habr.com/ru/post/1500161/


All Articles