I have a few a
elements which run functions via javascript and have a #
set as the href
however I have changed something recently that causes these to try and reload the page rather than do nothing and so breaks their functionality.
What can i look for that could cause this?
document.getElementById("link").onclick = function(){alert("do something javascript")};
<a id="link" href="#">Do Some JS</a>
Clicking this however reloads page and am unsure what i have done to cause this to reload the page.
I can't reproduce in the snippet, if i did i wouldn't be asking the question but something is causing these links to reload the page which is not expected behaviour.
So far i can only think or a quick and dirty fix:
$('a[href="#"]')).click(function() {
e.preventDefault();
});
I however would like to know what could be causing this issue to arise.
Ok i found it thanks for your help:
window.onpopstate = function(e){
if(e.state !== null) {
} else {
location.reload();
}
}
That will do it for sure.
I think it's so that as pages are heavily reliant on ajax there was no way to go back to where you had been.
I figured the easiest way was have the urls update on ajax changes so when i clicked back the url would change to last action and then cause page to reload correctly on pop state change.
I will change the code to:
window.onpopstate = function(e){
if(e.state !== null) {
} else {
if(window.location.href.substr(window.location.href.length - 1) != "#") {
location.reload();
}
}
}
This is normal behaviour of a
tags if you don't want them to reload your page or scroll to top of your page you should remove href
from your a
tags.
You can also stop them from reloading your page like this:
<a href="#" onclick="return false;">No reload</a>
<a href="javascript:void(0)">No reload</a>
In your function you need to use e.preventDefault()
or event.preventDefault()
. So for example:
function clickMe(e) {
e.preventDefault();
}
As per the most recent comment, you need to pass in the event to the function so it looks like this:
$('a[href="#"]')).click(function(e) {
e.preventDefault();
});
Note that this is an approach I wouldn't recommend since it will block all links and could cause more problems than intended. You'll want to use a specific class to target your anchors.
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