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

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();
}
}
}

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:
No reload
No reload

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.

try
<a onClick="callback();"></a>
just remove that href= "#"
It will not reload or refresh the browser

try javascript:void(0) instead #
eg.
Link
because without seeing some code we never know what cause this problem.

Related

Is it possible to add a javascript for/while loop for location.reload();

My Wordpress site has conflicting plugins. So when I click a page in the menu, it get stuck but fixes when the page has been re-loaded.
My approach is to auto refresh the page (the menu link that has been clicked) so the page will properly load.
After searching for couple of days, I haven't found the exact way to do it.
I use
location.reload(true);
but it keeps reloading. I tried also
location.reload(true);
window.stop();
but it stops loading before it completes the page load to 100%.
So my question is, can we add a loop to stop the reload?
example…
after 2 reloads, the js code will stop
Hopefully someone can help me. Thanks!
Try this piece of JavaScript, it stores the reload count in LocalStorage:
if(typeof(localStorage.getItem('rlcount')) == 'undefined'){
localStorage.setItem('rlcount', 0);
}
if(localStorage.getItem('rlcount') < 2){
localStorage.setItem('rlcount', localStorage.getItem('rlcount') + 1);
window.location.reload();
}else{
localStorage.removeItem('rlcount');
}
However, you should note that reloading a page is not a good fix for your bug, you should find the root cause.
While I would encourage you to try to fix the root problem causing the behavior you described, you could do something like the following to reload the page twice:
window.onload = function() {
if (!window.location.hash) {
window.location = window.location + '#loadedOnce';
alert("Reloading first time...");
window.location.reload();
} else if (window.location.hash === "#loadedOnce") {
window.location = window.location.hash.replace("#loadedOnce", "#loadedTwice");
alert("Reloading second time...");
window.location.reload();
} else if (window.location.hash === "#loadedTwice") {
// Page reloaded twice, do whatever...
}
}
This makes use of a hash in the URL, so it does not require using the localStorage API (although that is a perfectly fine approach too if the browser supports it, and might work better if you already have hashes in the URL).
Thank you for taking time to answer my question guys…
I found a simple way (not a loop though). Not sure if this is ok but it's working when I added "return".
location.reload();
return;
When adding this command. it simply reloaded once.

How to capture browser's back/forward button click event or hash change event in javascript?

I want to alert() when browser's back or forward button is clicked or hash is changed in javascript. I have tried this solution and it is working but it is causing problems on other links in webpage and submit each request twice on any link click event.
Is there any solution to capture it without using setInterval() function? So I need to capture hash change or back/forward button click event? I need a simple javascript code/function/property that should work in all modern browsers.
Any solution ?
Thanks
Not a good idea
Can you rather explain the reasoning behind this? We've all been down this road of preventing backs/forwards and similar and mangling with browser functionality.
It turns out though it's better to obey to browser and write your application in that way so these things become irrelevant. And it's also true that browsers are locking more and more things to client javascript apps so it's highly likely your app is going to fail after (few) browser upgrades.
Go with HTML5
HTML5 History spec may be exactly what you're after. It's the way things should work and be done in regard to Ajax applications and browser0s back/forward functionality. I suggest you check it out. See a working demo that does this rather nicely.
I believe this is the answer Robert Koritnik was looking for, I found it here: https://developers.google.com/tv/web/articles/location-hash-navigation
There is an event (window.onhashchange) that fires whenever the location hash has been updated or changed so all you have to do is set up an event handler using JavaScript to listen for this event and execute code based on the hash. This is basically how it is done:
function getLocationHash() {
return window.location.hash.substring(1);
}
window.onhashchange = function(e) {
switch(getLocationHash()) {
case 'state1':
execute code block 1;
break;
case 'state2':
execute code block 2;
break;
default:
code to be executed if different from case 1 and 2;
}
}
I have it working on my site:
http://www.designhandler.com
It is all dynamically changing content. No ajax yet but when I am finished it will be. I still use the window.location.hash to keep track of the site states. If you navigate through the site and then begin to use the back forward buttons to navigate once the site is in the history it will change the states dynamically like if the user was actually clicking through the nav, rather than needing to reload the page afterward.
It's this for hash or for redirection? What are you trying to do? This kind of action is usually highly intrusive.
You may want to try "onbeforeunload" event for this javascript before leaving the page
Edited
Actually, the link you provide is quite accurate.
var hash = location.hash;
setInterval(function()
{
if (location.hash != hash)
{
hashUpdatedEvent(hash);
}
}, 100);
function hashUpdatedEvent(hash)
{
switch(...);
}
Your link duplicate action problem would be corrected if you change
Go for it
function someFuncion()
{
doWhatever();
location.hash = 'somethingwasdone';
}
function hashUpdatedEvent(hash)
{
if(hash == 'somethingwasdone')
{
doWhatever();
}
}
By just (update the hash and let the "event" handle the action) :
Go for it
function someFuncion()
{
location.hash = 'somethingwasdone';
}
function hashUpdatedEvent(hash)
{
if(hash == 'somethingwasdone')
{
doWhatever();
}
}
Javascript provide the event popstate to capture browser's back/forward button click event -
window.addEventListener("popstate", function(e) {
// if a back or forward button is clicked, do whatever, like alert or anything
console.log('href => ', e.path[0].location.href);
// href => https://testdomain.com/demos/material/admin-app/#!/app/dashboard
console.log('hash => ', e.path[0].location.hash);
//hash => #!/app/dashboard
console.log('pathname => ', e.path[0].location.pathname);
//pathname => /demos/material/admin-app/
});
Read more on popstate

Why does page scroll up when href="#" is clicked?

I have a hyper link as such Link that i have to scroll down the page to get to. This hyperlink is only there to trigger an Ajax request. When ever i click this hyperlink the page scrolls all the way to the top! How can i fix this? I use # because anything else would reload the page. Am I using it wrong?
EDIT:
Its kind of hard for me to explain what am doing so if you run this you get the same problem that i am facing. Even after returning false.
<html>
<head>
</head>
<body>
Link
</body>
</html>
<script type="text/javascript">
document.getElementById("link").onmousedown = function(){
this.style.color="red";
return false;
}
</script>
add a return false; to the event handler assigned:
el.onclick = function() {
// do your code
return false;
}
Or the arguably more elegant way
function(e) {
e = e || window.event;
if ( e.preventDefault ) e.preventDefault()
else e.returnValue = false;
}
Have to tried javascript:void(0) in place of #?
Source:
Which "href" value should I use for JavaScript links, "#" or "javascript:void(0)"?
Edit:
Reason:
It prevents the browser from refreshing or navigating to another page.
http://www.tizag.com/javascriptT/javascriptvoid.php
The browser is trying to move to an anchor named #. There isn't any so it scrolls to the very top. To avoid this behavior do what meder mentioned.
you need to stop the event propagation when you click the anchor tag.
The browser is reading the # as an anchor, you ether have a link with an id of "someID" at the top of your page or no ID at all in which case it will just go to the top of the page by default (This seems to be the case for you). You will have to replace the # sign with something to stop this. I'm not sure what would be best, but Evan Mulawski's answer might work. I don't know if this will still allow your ajax code to run properly though.

Detect Browser Refresh in Javascript

I am curious if there is a way to detect the browser refresh event in javascript specifically. We are using the jQuery.address plugin to provide forward and back button functionality to AJAX functions. The problem I am facing is that this plugin does not seem to detect if the user has refreshed the page.
This code is executed each time the user moves forward or back in the browser history. I would also like it to exexute when the user refreshes.
$.address.init(function(event) {
}).change(function(event) {
SummaryDiv.SwapPanels(newPanelID);
}
Any ideas?
Along these lines, I had a page whose behavior I didn't want to repeat if refreshed, so I changed the hash programmatically as described in this answer.
checkRefresh: function() {
if (document.location.hash === '#visited') {
console.log('Refreshed');
return true;
} else {
document.location.hash = 'visited';
return false;
}
}
UPDATE
I found that at least Mobile Safari would ignore the hash if the refresh occurred automatically (e.g. page data expunged from cache before being viewed again). I ended up using a more complex solution described here.
A naive attempt of mine would be to simply store the current state into some cookie after each change and simply load them again on each page load.
Found this on the web for you...
Has both a javascript clever method along with a cookies method.
http://www.tedpavlic.com/post_detect_refresh_with_javascript.php
On a page refresh, the javascript is also reloaded. So couldn't you specify what you want to happen directly in jQuery's ready method?
I was able to force the change event code to run on refresh by
window.onload = $.address.update(function(){
...
})
In javascript you can do this:
page1.html
<script>
localStorage.removeItem('setear1')
</script>
page2.html
<script>
addEventListener('DOMContentLoaded', () => {
let vengoDeLaPaginaAnterior = localStorage.getItem('setear1')
if (vengoDeLaPaginaAnterior === null) {
localStorage.setItem('setear1', 1)
} else {
document.location.href = 'page1.html'
}
})
</script>
then: if user refresh page, return to previus page.

Force page reload with html anchors (#) - HTML & JS

Say I'm on a page called /example#myanchor1 where myanchor is an anchor in the page.
I'd like to link to /example#myanchor2, but force the page to reload while doing so.
The reason is that I run js to detect the anchor from the url at the page load.
The problem (normally expected behavior) here though, is that the browser just sends me to that specific anchor on the page without reloading the page.
How would I go about doing so? JS is OK.
I would suggest monitoring the anchor in the URL to avoid a reload, that's pretty much the point of using anchors for control-flow. But still here goes. I'd say the easiest way to force a reload using a simple anchor-link would be to use
where in place of $random insert a random number (assuming "dummy" is not interpreted server side). I'm sure there's a way to reload the page after setting the anchor, but it's probably more difficult then simply reacting to the anchor being set and do the stuff you need at that point.
Then again, if you reload the page this way, you can just put myanchor2 as a query parameter instead, and render your stuff server side.
Edit
Note that the link above will reload in all circumstances, if you only need to reload if you're not already on the page, you need to have the dummy variable be more predictable, like so
I would still recommend just monitoring the hash though.
Simple like that
#hardcore
an example
Another way to do that is to set the url, and use window.location.reload() to force the reload.
<a href="/example#myanchor2"
onclick="setTimeout(location.reload.bind(location), 1)">
</a>
Basically, the setTimeout delays the reload. As there is no return false in the onclick, the href is performed. The url is then changed by the href and only after that is the page reloaded.
No need for jQuery, and it is trivial.
My favorite solution, inspired by another answer is:
myanchor2
href link will not be followed so you can use your own preference, for example: "" or "#".
Even though I like the accepted answer I find this more elegant as it doesn't introduce a foreign parameter. And both #Qwerty's and #Stilltorik's answers were causing the hash to disappear after reload for me.
What's the point of using client-side JS if you're going to keep reloading the page all the time anyways? It might be a better idea to monitor the hash for changes even when the page is not reloading.
This page has a hash monitor library and a jQuery plugin to go with it.
If you really want to reload the page, why not use a query string (?foo) instead of a hash?
Another option that hasn't been mentioned yet is to bind event listeners (using jQuery for example) to the links that you care about (might be all of them, might not be) and get the listener to call whatever function you use.
Edit after comment
For example, you might have this code in your HTML:
example1
example2
example3
Then, you could add the following code to bind and respond to the links:
<script type="text/javascript">
$('a.myHash').click(function(e) {
e.preventDefault(); // Prevent the browser from handling the link normally, this stops the page from jumping around. Remove this line if you do want it to jump to the anchor as normal.
var linkHref = $(this).attr('href'); // Grab the URL from the link
if (linkHref.indexOf("#") != -1) { // Check that there's a # character
var hash = linkHref.substr(linkHref.indexOf("#") + 1); // Assign the hash to a variable (it will contain "myanchor1" etc
myFunctionThatDoesStuffWithTheHash(hash); // Call whatever javascript you use when the page loads and pass the hash to it
alert(hash); // Just for fun.
}
});
</script>
Note that I'm using the jQuery class selector to select the links I want to 'monitor', but you can use whatever selector you want.
Depending on how your existing code works, you may need to either modify how/what you pass to it (perhaps you will need to build a full URL including the new hash and pass that across - eg. http://www.example.com/example#myanchor1), or modify the existing code to accept what you pass to it from you new code.
Here's something like what I did (where "anc" isn't used for anything else):
And onload:
window.onload = function() {
var hash = document.location.hash.substring(1);
if (hash.length == 0) {
var anc = getURLParameter("anc");
if (anc != null) {
hash = document.location.hash = anc;
}
}
}
The getURLParameter function is from here
If you need to reload the page using the same anchor and expect the browser to return to that anchor, it won't. It will return to the user's previous scroll position.
Setting a random anchor, overwriting it and then reloading seems to fix it. Not entirely sure why.
var hash = window.location.hash;
window.location.hash = Math.random();
window.location.hash = hash;
window.location.reload();
Try this its help for me
<a onclick="location.href='link.html'">click me</a>
In your anchor tag instead of
click me
As suggested in another answer, monitoring the hash is also an option. I ended up solving it like this so it required minimal code changes. If I had asked the original question, I believe I would have loved to see this option fully explained.
The added benefit is that it allows for additional code for either of the situations (hash changed or page loaded). It also allows you to call the hash change code manually with a custom hash. I used jQuery because it makes the hash change detection a piece of cake.
Here goes!
Move all the code that fires when a hash is detected into a separate independent function:
function openHash(hash) {
// hashy code goes here
return false; // optional: prevents triggering href for onclick calls
}
Then detect your hash for both scenarios like so:
// page load
$(function () {
if(typeof location.hash != typeof undefined) {
// here you can add additional code to trigger only on page load
openHash(location.hash);
}
});
// hash change
$(window).on('hashchange', function() {
// here you can add additional code to trigger only on hash change
openHash(location.hash);
});
And you can also call the code manually now like
Magic
Hope this helps anyone!
Try this by adding simple question mark:
Going to Anchor2 with Refresh

Categories