I am facing a problem. I have a web page where I use back button anchor link and the code used is ONCLICK="history.go(-1)"
. The same page has many anchor links and the related sections.
When I go to a page containing back button and click back button immediately, then back button works fine.
If I go to a page containing back button, then hit anchor link that points to a section in the same page and then hit the back button, then it never goes to previous web page, instead goes to the section url.
I am facing a problem. I have a web page where I use back button anchor link and the code used is ONCLICK="history.go(-1)"
. The same page has many anchor links and the related sections.
When I go to a page containing back button and click back button immediately, then back button works fine.
If I go to a page containing back button, then hit anchor link that points to a section in the same page and then hit the back button, then it never goes to previous web page, instead goes to the section url.
Share Improve this question edited May 17, 2012 at 12:46 kapa 78.7k21 gold badges165 silver badges178 bronze badges asked May 17, 2012 at 12:30 sridharsridhar 1,1575 gold badges33 silver badges61 bronze badges 4- 1 This is how it should work. An anchor link is a valid part of history. – kapa Commented May 17, 2012 at 12:35
- Thanks .. bazmegakapa. How to implement the above. any idea ? – sridhar Commented May 17, 2012 at 12:37
- 2 Consider using location.replace() then for your anchor links. – Ja͢ck Commented May 17, 2012 at 12:37
- Thanks .. Jack. How do to get the previous URL to use location.replace. any idea? – sridhar Commented May 17, 2012 at 14:00
3 Answers
Reset to default 2Through the new History API, you can manipulate the browser history.
History.js helps you achieve this in a cross-browser way.
I have quickly created a small fiddle that illustrates it working and uses jQuery for event handling (this is not production code, just a demo, works in my Chrome).
$('.anchor').click(function () {
history.replaceState({}, '', this.href);
});
If so you could use javascript to solve this by simply using this line.
Make use of the history.go()
JavaScript function as below:
<a href="javascript:window.history.go(-1);">Go back</a>
Maybe you can try a counter that counts how many times a "section" link is clicked
Maybe something like (with jQuery but maybe some kind person will go and change this code to nice plain JavaScript):
var count = 0;
var historyValue = -1;
$(".sectionlinks").click(function () {
++count;
window.historyValue = -(count + 1);
})
And all your section links have a sectionlinks
class.
Then you can do on your back link:
<a onclick="history.go(historyValue)">My Back Link</a>
See this fiddle for a demo: http://jsfiddle/RRcyF/2/