I'm working on a web application which is a traditional aspx (asp.net) web forms app but has had some angular 6 apps incorporated into it.
I've been tasked with fixing a bug that causes the browser to refresh when clicking on an anchor element with a href="#".
I'm not sure what's causing the whole page to reload.
Strangely when I open dev tools in Chrome, choose the network tab and select disable cache the page only refreshes the first time I click a link and any other subsequent clicks work fine. This might be to do with the fact that after the first time I click it the browser url now contains the # at the end of it.
I know this seems a bit random but I wondered whether anyone had any theories on what may cause the reload in the first place.
It's hard to tell what could be causing this without seeing any code. The most common solution I've used when I get this behavior is a prevent default. You can do something like
<a href="#" (click)="$event.preventDefault()">
Or if you already have a click event then pass in $event as a parameter to your function then preventDefault in the function you are calling. This would look like:
Html
<a href="#" (click)="someFunc($event)">
and in your ts:
someFunc(event) {
event.preventDefault();
// rest of your code here
}
This answer is related to the question and it's the first one that comes up in Google so I hope this is useful.
I have some external web components that use regular anchor tags with hrefs that point to routes in my angular app. Clicking the href causes a full page reload. This is because I'm not using routerLink - but, in my case, I can't.
So, my work around is:
#HostListener('window:click', ['$event'])
onClick(e: any) {
const path = e.composedPath() as Array<any>;
const firstAnchor = path.find(p => p.tagName.toLowerCase() === 'a');
if (firstAnchor && !firstAnchor.hasAttribute('routerlink')) {
const href = firstAnchor.getAttribute('href');
this.router.navigateByUrl(href);
e.preventDefault();
}
}
Depending on your application, you might need to make some other checks e.g. is the target _blank, is it an external url etc.
change your a tag code as below
A Tag
this will invoke yourClickEvent(); without page reload
check the stackblitz here stackblitz
If you don't want to reload the page use $event.preventDefault()
<a href="#" (click)="$event.preventDefault()">
Try using debug tools to select the element, then click Event Listeners and then the Click event to see what is listening. Perhaps you can track it down that way.
You could also simply paste this into the console to trigger a break, and then click any of the offending elements:
['unload', 'beforeunload'].forEach(function (evName) {
window.addEventListener(evName, function () {
debugger; // Chance to check everything right before the redirect occurs
});
});
source: Break when window.location changes?
As you are using angular routes, try to use this notation:
<a [routerLink]="['./']" fragment="Test">
As explain by this comment: https://stackoverflow.com/a/38159597/4916355
use href="javascript:void(0);"
The reason you’d want to do this with the href of a link is that normally, a javascript: URL will redirect the browser to a plain text version of the result of evaluating that JavaScript. But if the result is undefined, then the browser stays on the same page. void(0) is just a short and simple script that evaluates to undefined.
Use [routerLink] instead of using href = "", and use click event to call your calling method in the typescript file.
ex:
// downloading the file based on file name
<a [routerLink]="'file://' + 'path'" (click)="downloadFile(templateDocument.fileName)">{{downloadDocuments.fileName}}</a>
Since you have mentioned the web app is asp.net webforms, can you please let us know
Whether the link is asp.net hyperlink control. If so,
AutoEventWireUp could cause the link to be automatically submitted:
Please have a look at this link
If you do have asp.net server controls on the page, then you could disable by setting
#Page AutoEventWireup="false"
For the entire project, this can be disabled by setting in web.config:
Related
I have not been able to find any discussion of what I'm struggling with on this site or any other, but perhaps I'm not asking the right question. I'm working on a web interface for a wireless speaker powered by the raspberry pi, and (as I inherited it) almost all the POST requests are done with calls to $.ajax. $().ready() is as follows:
$().ready(function (){
$(document).ajaxStart(function (){
$.blockUI({ message: '<img id="loadimg" src="img/loading.gif" width="64" />'});
}).ajaxStop($.unblockUI);
$("nav.setup-nav a").not("[target='_blank']").on("click", function (event){
event.preventDefault();
var href=$(this).attr('href');
$.ajax({
type:"POST",
url:href,
success:function (data){
$(".contentPanel").html(data);
$(this).blur();
$("html, body").animate({ scrollTop:100, scrollLeft:400}, 600);
},
});
return false;
});
});
Which forces all the content of the linked-to pages in the nav menu to load inside a div in the center of the page. That is, except for pages with target="_blank" attribute. This is so event.preventDefault and the UI blocking stuff doesn't get called when linking to an external page that we want to load in a new window. I'll try to concisely describe my issue: One of the menu items is (conditionally) a link to a web-based MPD client, which we definitely do NOT want to load inside a div on the same page, and thus has target="_blank" attribute. The problem is the user can also choose to enable or disable the MPD daemon through the web-interface. PHP handles the setting of all these kinds of state variables. Basically like this:
if ($config->is_flag_set($MPD_FLAG))
{
echo '<li><a target="_blank" id="mpd" href="rompr/">Local Playback Web Interface</a></li>';
}
else
{
echo '<li><a id="mpd" href="local-disabled.php">Local Playback Web Interface</a></li>';
}
and so when the page first loads, if the MPD daemon is not running the link to the web interface is pointed to a page that explains MPD is not enabled. This link does NOT contain the target="_blank" attribute. However, if one navigates to the settings form and switches on MPD, there is logic to replace the href and target attributes of that particular link, so theoretically all should work as if the page had loaded initially with the MPD flag on (if that is clear!). The problem is that when the "replaced" link with target="_blank" (set by .prop() or .attr(), I've tried both and it doesn't seem to make a difference) is clicked, the page still loads inside the div!I tried duplicating the click handler that's defined within $().ready and putting it in another function which I call after the link attributes are set, but it still doesn't work as I imagine it should! Just to verify that I wasn't crazy, I used .each() to print all the links that did and did not have the target="_blank" attribute and that all corresponds to what I believe it should be. Why is the replaced link not getting treated as if it has a target="_blank" attribute in the click handler? By the way, Going the other way and removing the target="_blank" attribute if MPD is turned off, works like a charm. Thanks so much in advance for any answers, and my apologies if I have duplicated a previous question!
Cheers,
Events are always tricky anytime you have to reload elements with ajax. The best way I've found is to attach the event to some container element that will not reload:
$('#always_present_container').on('click', "nav.setup-nav a", function (event){
if($(this).attr('target') != '_blank'){
...
}
});
that way the element is checked for the attribute when its container is clicked. When you set up $('element').click() the selector is checked on the page load and the events attached then, so when you reload something via ajax the new element doesn't get this event attached.
Note: normally you could avoid the conditional statement in the function, but I didn't know of an easy way to filter by target in a css selector.
This code works fine in FF, it takes the user back to the previous page, but not in Chrome:
Link
What's the fix?
You should use window.history and return a false so that the href is not navigated by the browser ( the default behavior ).
Link
Use the below one, it's way better than the history.go(-1).
Go TO Previous Page
Why not get rid of the inline javascript and do something like this instead?
Inline javascript is considered bad practice as it is outdated.
Notes
Why use addEventListener?
addEventListener is the way to register an event listener as specified
in W3C DOM. Its benefits are as follows:
It allows adding more than a single handler for an event. This is
particularly useful for DHTML libraries or Mozilla extensions that
need to work well even if other libraries/extensions are used. It
gives you finer-grained control of the phase when the listener gets
activated (capturing vs. bubbling) It works on any DOM element, not
just HTML elements.
<a id="back" href="www.mypage.com"> Link </a>
document.getElementById("back").addEventListener("click", window.history.back, false);
On jsfiddle
Try this:
Link
Try this dude,
<button onclick="goBack()">Go Back 2 Pages</button>
<script>
function goBack() {
window.history.go(-2);
}
</script>
It worked for me. No problems on using javascript:history.go(-1) on Google Chrome.
To use it, ensure that you should have history on that tab.
Add javascript:history.go(-1) on the enter URL space.
It shall work for a few seconds.
javascript:history.go(-1);
was used in the older browser.IE6. For other browser compatibility try
window.history.go(-1);
where -1 represent the number of pages you want to go back (-1,-2...etc) and
return false is required to prevent default event.
For example :
Link
Use Simply this line code, there is no need to put anything in href attribute:
Go TO Previous Page
Using a link with a URL to one page and having an on-click event that overrides it is not a good idea. What if the user opens the link in a new tab?
Consider:
<button id="back">Go back</button>
<script>
document.querySelector("#back").addEvenetListener("click", e => {
history.go(-1);
});
</script>
Or if you must use a link, at least:
Go back
Because this topic turn out to interdisciplinary (but still is about user experience) I'm curiuos what think about this an javacript developers.
My site handling a tags with href starting with # as ajax request. If request was successfully then it's change document hash to appropiate. Now I want to implement action links that call internal js function like going to site top, but I don't want javascript:myAction() reference, because most browsers is showing hint with referencing url when you're over the link. Probably I can use and successfully handle own url schema like action:myAction, but it's not enough solution - user was still hinted about magic url. Another option is using custom attribute like action="myAction" with href as custom string e.g. href="Go to top", but what with browsers compatibility? Last solution is to using a span styled as link to perfom action - user is not hinted about any url, but this is a part of link functionality what suggest that perform an action (going to url default).
What is better and why?
<script>
if(window.addEventListener)//Chrome, Firefox and Safari
document.getElementById('myLink').addEventListener('click',function(e){
var e = e || event;
e.preventDefault();
window.location = destiny;
});
else//IE and Opera
document.getElementById('myLink').attachEvent('onclick',function(e){
var e = e || event;
e.preventDefault();
window.location = destiny;
});
</script>
Link
You should make your links work first without JavaScript. Then you don't have to worry about someone clicking <a href='/customers'>Customers!</a>. It works nicely and is accessible. Once you've reached this point you put the JavaScript on top to enhance the user experience. How you hook all of these up is up to you - say you want to handle deletes in a generic way, you might have links that look like this:
<a href='/customers/2' class='delete'>Delete customer</a>
<a href='/customers/2' data-action='delete'>Delete customer</a>
Or if it's specific per link, you set the id and wire it up that way:
<a href='/customers/2' id='delete'>Delete customer</a>
All of this wiring up should be done in an external JavaScript file.
I would do this by first writing everything in a way users without JS can use it, like
Go to top
Then I would take JS to enhance it immediatly after the DOM is loaded. First by adding the onclick event, then removing the href, to avoid any link hint (any other content than links probably not pass any validator) and finally a new style attribute that the cursor becomes a pointer on hover.
It is part of the very useful programmatic progressive enhancement structure. This way I get valid and compatible code as well as a comfortable behaviour.
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
Can we use 2 different url on same for javascript disabled and enabled condition
If javascript is enabled then link should be <a href="link1">
and If javascript is disabled then link should be <a href="link2">
You could set the JS disabled URL in the markup, then on page load use JS to replace the url with the enabled URL.
HTML:
<a id="id" href="js_disabled_url" />Link</a>
jQuery example:
$(function() {
$('#id').attr('href','js_enabled_url');
});
This should degrade gracefully.
Yes, just write a JavaScript which finds the element you want to change the href of when the page has loaded.
Example using JQuery:
$(function () {
$('a.changeable').each(function () {
$(this).attr('href', 'http://google.com/lol');
});
});
(Untested, but you get the idea.)
So basically, if the user has disabled JavaScript, the default link is used, otherwise the new URL given by the script is used. So your HTML should contain the link that should be used when JavaScript is disabled.
If I understand you correctly, you can have one url on the html page, and if javascript is working, have the javascript change the url on the anchor.
That way you can ensure that the second url only works if javascript is enabled.
The problem is that if javascript was enabled when the page was loaded, and later disabled then you won't know.
But, if you just have an onclick on the anchor, then you can change the url when it is clicked on, then it will always work correctly, as, if they disable javascript after the page is loaded it will still go to the non-javascript url, and if the onclick works then it will go to the other url.