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
Related
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:
In web site I have to add "Back" button or Link URL which will redirects to me previously visited page.
Currently I have added below code, but it doesn't always work.
<i>Back</i>
I observed that it is not working in Google chrome.
<script>
function sample(){
window.location.href = window.history.back(1);
}
</script>
<input type="button" value="trying" onclick="sample()"/>
I have tested here it is working test ... :)
Event this work as same
<i>Back</i>
Try this :
<input action="action" type="button" value="Back" onclick="history.go(-1);" />
The following was an incorrect assumption by me
The value passed to onclick should be a function to call when the link is clicked. You are passing window.history.back() which is the value returned by the back function.
Try the following.
<i>Back</i>
Turns out I assumed, incorrectly, that the value of onClick should be a function to call on click. As Brian North and putvande pointed out in the comments it should be the javascript code to run when the event is triggered.
Suggestion
However one should generally avoid binding events in the way you are doing as it couples presentation, HTML, too tightly with the javascript. Instead one should bind the click listener from an external javascript file using for example addEventListener or jQuery.on.
jQuery example
HTML
Back
Javascript
$(function() {
$("#history-back").on("click", window.history.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.
I have a HTML/JavaScript project that holds a few dozen anchor tags; each of the anchor tags calls the same JavaScript function, but with a different parameter.
Everything looks good in Firefox and Chrome, but in Internet Explorer (IE) the page seems to reload (flicker) every time I click an anchor tag (like the one shown below). How can I make IE stop reloading/flickering? I would prefer not to rewrite the whole script. I have tried onclcick='javascript... and href='javascript...,but both have the same problem (although onclick seems a little better).
<a onclick='javascript:foo(22)'></a>
Try <a onclick='foo(22); return false;'></a>
Also, javascript: is pointless in event attributes as it just defines a label.
Simpler to use jQuery:
<script>
$('.action').click(function(){
yourfunction($(this).attr('rel');
return false;
});
</script>
href="#" onclick="closeOrCancel() and history.go(-1) in that js method doesnt work in Chrome (neither history.back())
It works with href="javascript:closeOrCancel()" , but Opera doesn't allow href="javascript:...
How to make history go back using onclick= "myFunction()" ?
Edit: closeOrCancel() returns false
Adding a return false; to the onclick code seems to be enough:
Go Back
You're wrong about two things here:
Opera allows href="javascript:...
history.go(-1) works in Chrome.
Please provide source for your script, since the problem is clearly in it and not the browsers.
Just put this in a html file and open it to see for yourself:
<script>
function goback() {
history.go(-1);
}
</script>
goback
tt
First click the "tt" link, then "goback". See the hash change. It works fine, although I'd personally recommend against using javascript in href's.
I used history.go(-2); to go back to step 1 in chrome.