Avoid a Link to Reload the Page in JavaScript

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

Avoid a link to reload the page in Javascript

everyone.

I've found the solution, which worked for me:

<input class="tableInput" type="text" value="Table input" onkeypress="return tableInputKeyPress(event)" />
<script type="text/javascript">function tableInputKeyPress(e){ e=e||window.event; var key = e.keyCode; if(key==13) //Enter { //do you task here... return true; //return true to submit, false to do nothing }}</script>

Prevent page reload when blank link is clicked?

Check if row['slink'] is present, else replace href with javascript:alert(...)(This won't do page reload for blank href, and show an alert):

var href = row["slink"].trim().length > 0 ? row["slink"] : "javascript:alert('File Not Yet Available')"


'<a href="'+href+'"><button type="button" class="btn btn-info " data-row-id="' + row.id + '">Download</buttn></a> ';

JavaScript is there a way to stop href="#" to refresh a page ? nyroModal

For my projects, I add this code to prevent the jerk ( as the page scrolls to top ) when an anchor with href=# is clicked:

$(document).ready(function(){
$("a[href=#]").on("click", function(e){
e.preventDefault();
});//a[href=#] click
});//document ready

This way you need not go to every anchor tag and disable this. In case, there are some exceptional anchor tags, you can easily exclude those using some selector or adding some condition inside this click handler.

And if you don't want this behaviour, you can directly remove these lines from your javascript, there is no need to modify your html code.

Prevent anchor tag reloading page on @click in Vue.js

Based on your code I would try this, but if it was me, I would use the router.

<template>
<p>Please click <a @click="stopProcess">here</a></p>
</template>

<script>
export default {
methods: {
stopProcess(){
var page = window.location.origin + "/pages/page.pdf"
window.open(page);
}
}
};
</script>

How to prevent page refresh when <a> tag clicked?

window.location.hash="inbox/1" can update the hash value in the url. This can be done with the event preventDefault code.



Related Topics



Leave a reply



Submit