href must not reload
If you don't want it to behave like a link, then don't use a link tag. Doing so hurt accessibility of a page, and you don't want that. There are other ways of browsing a website than a browser (think about the screen readers), which relies on the semantics of the page elements. Use a span
if you simply want to apply a style.
If you still want to use an anchor, you can use this -
<a href="#" onclick="return false;">Link</a>
This will prevent your page reloading.
href must not reload
If you don't want it to behave like a link, then don't use a link tag. Doing so hurt accessibility of a page, and you don't want that. There are other ways of browsing a website than a browser (think about the screen readers), which relies on the semantics of the page elements. Use a span
if you simply want to apply a style.
If you still want to use an anchor, you can use this -
<a href="#" onclick="return false;">Link</a>
This will prevent your page reloading.
Add url to href on a tag but do not want to reload behavior
You need target="_blank"
for this.
<a href="www.google.com" target="_blank">Click</a>
Prevent a link to reload page
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
How to stop loading the page after clicking on an href link in html?
add javascript:void(0)
in your href attribute, this will prevent default action of element.
<a href="javascript:void(0)" onclick="alert('ITEM ADDED TO WATCHLIST')">Add to your watchlist</a>
Related Topics
How to Display on HTML Page in Another HTML Page in Angular 4
Angular - Show Empty Row by Default in Drop Down List and Disable Button
Make Div (Height) Occupy Parent Remaining Height
How to Make Vertical Lines Between List Items Using CSS
Children Not Staying Inside Parent Divs
How to Vertically Center a Div Element For All Browsers Using Css
What Are the Recommendations For HTML ≪Base≫ Tag
Css: Width in Percentage and Borders
Css - How to Make the Checkbox and Label in One Line
Prevent Child Div from Overflowing Its Parent Container When Resizing the Page
How to Disable Hover Effect for Active Link
Grid Items Overflow Out of Parent Container Using CSS Grid
How to Change Pressed Item Background Color in Ion-List on Ionic
Bootstrap Row With Columns of Different Height
How to Vertically Align Elements in a Div
Can't Scroll to Top of Flex Item That Is Overflowing Container