Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A Elements with HREF="#" causing page to reload on click

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.

The problem

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.

My Quick Fix

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();
        }
    }
}
like image 458
harri Avatar asked Dec 21 '17 14:12

harri


2 Answers

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>
like image 105
Zvezdas1989 Avatar answered Oct 19 '22 08:10

Zvezdas1989


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.

like image 3
kawnah Avatar answered Oct 19 '22 07:10

kawnah