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?
If you put # inside the href like then the link will not refresh or reload when clicked.
Just use "#/" instead of "#" and the page won't jump. Save this answer.
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? 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”); });
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:
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+.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With