Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent a link to reload page

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?

like image 578
Miguel Moura Avatar asked Sep 02 '13 14:09

Miguel Moura


People also ask

How do I stop a link from reloading the page?

If you put # inside the href like then the link will not refresh or reload when clicked.

How do I stop clicking links from jumping to top of page?

Just use "#/" instead of "#" and the page won't jump. Save this answer.

How do I stop a page from refreshing in HTML?

Use the preventDefault() method on the event object to prevent a page refresh on form submit in React, e.g. event. preventDefault() . The preventDefault method prevents the browser from issuing the default action which in the case of a form submission is to refresh the page. Copied!

How do I stop page reload/refresh on hit back button?

How do I stop page reload/refresh on hit back button? You have to detect browser back button event and pass as an input of the page you want do prevent URL reload that indicates you if you came from a back button click. this code: $(window). on('popstate', function(event) { alert(“pop”); });


1 Answers

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:

  • MDN: event.preventDefault()
  • jQuery: Selectors

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

like image 66
Sergio Avatar answered Sep 17 '22 15:09

Sergio