Refresh with back button when using anchor [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Handle URL anchor change event in js
How to do awesome refreshless page changes like GitHub
In my app I'm using this very simple code to add a hashtag:
<a href='#test'> <input type='submit'></input>
I would like the page to refresh when I press the back button. For now, it only goes from www.mysite.com/#test to www.mysite.com.
I saw different questions on this topic, but I didn't find how to accomplish that.
Thank you for your help.

A simple way would be to wait for the hash change event to occur and then react to it. Whenever the # changes, the function will be called and if the hash is empty, the page is going to be reloaded.
window.addEventListener('hashchange', function() {
console.log(window.location.hash);
if('' === window.location.hash) {
console.log('reload');
//window.location.reload();
}
});
http://jsfiddle.net/kcKLE/1/
I'd suggest using a library like jQuery for the event-binding stuff, since addEventListener doesn't work in any browser. (Hello IE)
https://developer.mozilla.org/en/docs/DOM/element.addEventListener
If you need something fancier, there is also a history api around.
https://developer.mozilla.org/en-US/docs/DOM/Manipulating_the_browser_history

I just found how to accomplish that. I'm using the onhashchange functionality. Here is my code:
document.body.setAttribute("onhashchange", "update()");
function update() {
if('' === window.location.hash) {
window.location.reload();
}
};
So when I press the back button the hash disappears and the page reloads.
Thank you for the hints everybody.

Related

Reset dropdown at page refresh or back/forward browser navigation

Is there a simple command to restart all, or some included javascripts? The problem I´ve got is that by refreshing page or pressing the back/forward key in the browser, some javascripts look like cached.
Maybe like codepen it does?
UPDATE:
I found out, that this is only a problem for my "dropdowns". So I have to reset them, if I refresh the browser and/or press back/forward. Any simple way?
UPDATE:
Ok, that works for me:
$(':input').not(":button").val('');
});
No, I found out that this is a "dropdown" problem - so, I want to
reset them by browser refresh and/or forward/backward.
To reset dropdowns to default value, you could use:
$(window).on("pageshow", function() {
$('select').prop('selectedIndex', function () {
var selected = $(this).children('[selected]').index();
return selected != -1 ? selected : 0;
});
});
This is because the browser used a cached version of the page when you clicked the back button, it is called a bfcache.
You could try to add an empty unload handler like $(window).unload(function(){}); to disable the cache.
More info here: http://madhatted.com/2013/6/16/you-do-not-understand-browser-history

reload to top of page [duplicate]

This question already has answers here:
How to scroll to top of page with JavaScript/jQuery?
(28 answers)
Closed 8 years ago.
SOLVED
add this to the html:
<body onload="location.href='#menu'">
Its the only solution and not a duplicate of the scroll question....pff.
I have edited this question in hopes that the SO community would revisit it. None of the solutions in the supposed duplicate question work or I am using them incorrectly. I posted my code with two of the solutions to show that I am trying. Please help!
Super basic javaScript question I can't find.....I'm learning from trial, mostly error, and StackOverflow.
When I refresh I want to return to the top of the page (F5 or browser reload or any other way the page can be reset). I believe this was the 'old' way browsers worked but when I refresh I stay in the same place on the page. I'm testing in Chrome. Of course I would like this behavior in all browsers.
In this case I am building a single page app. Most mobile users will never use the refresh/reload as it is buried in the hamburger, but I would like to handle this event by going back to the home state. In this case the <div data-role="page" id="menu">.
I am using jquery but I want to make sure and learn javascript.
I thank you all.
code:
document.ready = init;
function init(){
var button = $('#facultyButton')
,facList = $('#facultyList')
,search = $('#facSearch')
,monikerBox = $('.monikerBox')
,events = $('#events')
,ajaxString = "http://stage.webscope.com/veith/dev/ajax.pl?"
,html = "";
//executed on init
console.log('page init');
$('html').scrollTop(0);
//events
$(window).on('load',function(){
$('html, body').scrollTop(0);
});
button.click(function(){
var value = "a";
The window's load event only runs once right after the page is done loading. So this way you can be sure that after the page loads no matter what reason (first view or refresh) it will run.
$(window).on('load', function(){
$('html, body').scrollTop(0);
});

Jquery mobile Pre-loaded page Stops working [duplicate]

This question already has an answer here:
jquery mobile autocomplete different behavior at loading page
(1 answer)
Closed 8 years ago.
My actually problem is below.I would be happy if this is solved.
I Want to know why jquery Preloaded url stops working.Below are steps to replicate my problem.
visit http://www.andymatthews.net/code/autocomplete/ .
Type "m"
You get list of names.Click any one.
For example i clicked http://www.andymatthews.net/code/autocomplete/target.html?term=Maryland.
Now why Select tool is not working after page preload.
If i reload http://www.andymatthews.net/code/autocomplete/target.html?term=Maryland It works fine
7. But if its preloaded whats the reason it stops working.
If that cannot be resolved , Tell me if any function available to stop the preload for single page.
i think this works, but you could use the data-ajax="false" attr on links and form actions
You have placed selectmenu change event inside .ready(), which shouldn't be used in jQuery mobile. The equivalent event is pageinit.
Also, instead of using window.location.href, use $.mobile.chagnePage() to activate Ajax navigation that jQuery Mobile uses.
$(document).on("pageinit", "#mainPage", function () {
$("#examples").on("change", function () {
var page = $(this).val();
setTimeout(function () {
$.mobile.changePage(page);
}, 100);
});
});
Just update your code.js on event handler to:
$('body').on('change', '#examples', function(e, ui) {
It'll work! Tested here.

Call a JavaScript Function when Back Button of Browser is Clicked [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Best way to detect when user leaves a web page
How can I call a javascript or jQuery function when back button of browser is clicked?
I have seen some solutions but none of them worked for me.
Can anybody show me some example code?
In jQuery try this :
$(window).unload( function ()
{
// put your code here
});
In javascript :
window.onbeforeunload = function () {
// put your code here
}
<body onUnload="yourFunction();>
<!-- ... -->
</body>
You can use history.replaceState() (see browser support) to modify the previous URL you visited to the current page with an added parameter of your choosing like for instance redirect=<URL of previous actual previous page> (you can maybe get this URL from the referer?), then detect the parameter in document ready and perform the required actions.
This is just an untested theory, I might elaborate later on when I get to test it.

HTML anchor link with no scroll or jump

I have various links which all have unique id's that are "pseudo-anchors." I want them to affect the url hash value and the click magic is all handled by some mootools code. However, when I click on the links they scroll to themselves (or to the top in one case). I don't want to scroll anywhere, but also need my javascript to execute and to have the hash value in the url update.
Simulated sample code:
button 1
button 2
Home
So if you were to click on the "button 1" link, the url could be http://example.com/foo.php#button1
Does anyone have any ideas for this? Simply having some javascript return void kills the scrolling but also kills my javascript (though I could probably work around that with an onclick) but more importantly, prevents the hash value in the url to change.
The whole point of an anchor link is to scroll a page to a particular point. So if you don't want that to happen, you need to attach an onclick handler and return false. Even just adding it as an attribute should work:
button 1
A side of effect of the above is that the URL itself won't change, since returning false will cancel the event. So since you want the URL to actually change, you can set the window.location.hash variable to the value that you want (that is the only property of the URL that you can change without the browser forcing a reload). You can probably attach an event handler and call something like window.location.hash = this.id though I'm not sure how mootools handles events.
(Also you need all of the IDs to be unique)
You can use the code below to avoid scrolling:
linktxt
I'm probably missing something, but why not just give them different IDs?
button 1
button 2
Home
Or whatever convention you'd prefer.
Also, preventDefault
$(your-selector).click(function (event) {
event.preventDefault();
//rest of your code here
}
I found the solution. Here I save an old location from calling href
and restore it after scrolling
<script language="JavaScript" type="text/javascript">
<!--
function keepLocation(oldOffset) {
if (window.pageYOffset!= null){
st=oldOffset;
}
if (document.body.scrollWidth!= null){
st=oldOffset;
}
setTimeout('window.scrollTo(0,st)',10);
}
//-->
</script>
and in body of page
<a href="#tab1" onclick="keepLocation(window.pageYOffset);" >Item</a>
Thanks to sitepoint
An easier way would probably be to add it as a GET. That is, http://example.com/foo.php?q=#button1 instead of http://example.com/foo.php#button1
This won't have any effect on how the page is displayed (unless you want it to), and most scripting languages already have tools in place to easily (and safely) read the data.
Well here we are 7 years after this answer was published and I found a different way to make it work: just point the window.location.hash to a non-existent anchor! It doesn't work for <a>s but works perfectly in <div>s.
<div onclick="window.location.hash = '#NonExistentAnchor';">button 1</div>
Worked fine in Chrome 56, Firefox 52 and Edge (IE?) 38. Another good point is that this doesn't produce any console errors or warnings.
Hope it helps somebody besides me.
There is a solution without any JavaScript at all:
I will not jump to the top
Use
button 1
where
function setHash(hash) {
event.preventDefault();
history.pushState(null, null, "#"+hash);
}
event.preventDefault() stops browser from what it normally would do on clicking, and history.pushState adds to the sessions history stack.
For further discussion, see here and here

Categories

Resources