I have a single page website. If click one of the navbar tabs, lets say 'contact us' the site will scroll down to the contact section. The problem is, if I refresh the site now it will automatically scroll down to the contact section each time. I want the site to scroll to the top of the page every time I refresh. The reason this is happening is because the address bar is changed to ...index.html#contact-area.
I tried the code below but the site gets caught in an infinite refresh loop.
<script>
window.location.replace("index.html");
</script>
I also tried the following but it doesn't work. It starts to scroll up then stops.
<script>
window.onbeforeunload = function () {
window.scrollTo(0, 0);
}
</script>
One option is to attach an event listener to the anchor instead, and instead of changing the page hash, call scrollIntoView on the #contact-area:
anchor.addEventListener('e', (e) => {
e.preventDefault(); // don't change page hash (unless JS disabled...)
document.querySelector('#contact-area').scrollIntoView();
});
Related
On Chrome, when I refresh while not at the very top of the page, the $(window).one('scroll' function is triggered immediately upon page load. I have a landing page that disappears when the user scrolls. But the landing page is disappearing immediately if I refresh the page while not at the top.
I tried adding
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
above the $(window).one('scroll' but that didn't work.
How can I reset the page to the top BEFORE Chrome reads the $(window).one('scroll' function?
Or is there a better solution?
That's actually correct behavior, the browser will scroll the page, and in normal circumstances we want to know about it, so it's normal the event is fired.
Unfortunately, when this event will fire isn't very well specified, so we have to resort on some magic numbers like
onload = (evt) => setTimeout(() => {
addEventListener("scroll", callback, { once: true });
}, 1000); // hopefully 1s after full page load the browser will have computed the new scrolling position
but that may very well fail, moreover if there is a lot of content being dynamically added in the page at load time.
If this is a deal breaker for you, maybe you'd be interested in preventing the page from restoring the scroll position at load, for this you can use history.scrollRestoration = "manual".
Another option would be to only listen to scroll events that do happen inside your landing page, instead of listening to every ones that happen in the page, and to reset this wrapper's scroll position after you hide the landing page, so that at the next reload the browser doesn't need to restore it.
I want to navigate inside the page with an animation using Javascript, but also change the URL so the user can click "back" to go back to the previous "page".
I have no idea how to approach this. Do I put the content I'm navigating to on a new html page, or on the same page?
What I've tried so far:
Some Other Page
This will completely reload to someOtherPage, and won't allow animations.
Some Other Page
<script>
function animateToOtherSection() {
//things like fade in/out or scroll
}
</script>
This works if the content I'm navigating to exists in this page, which is okay, but the URL won't be changed (except for the additional #).
If i try to change window.href in Javascript, the entire page reloads, which is not desired.
This question was inspired by some websites like this. When the See our projects button is clicked, although it as an anchor element, the page doesn't reload, but a fade out/in executes and the navigation bar above stays throughout. If I click the 'back' button in my browser, another animation takes me back to the splash screen.
Note: This is not an option:
Some Other Page
I don't want to just scroll to an element, but manipulate and show/hide a lot of elements on the screen.
Thanks in advance for the answers!
The DOM window object provides access to the browser's history through the history object. It exposes useful methods and properties that let you move back and forth through the user's history, as well as -- starting with HTML5 -- manipulate the contents of the history stack.
https://developer.mozilla.org/en-US/docs/Web/API/History_API
Load data from the server and place the returned HTML into the matched element.
http://api.jquery.com/load/
You can make it easy here is example:
HTML:
<button id="changeUrl">See our projects</button>
JavaScript:
$('#changeUrl').click(function () {
history.pushState({}, 'Title', '/Url/Test');
$(document).load('/url html');
});
Also you can add animation for example :
$('#changeUrl').click(function () {
$('body').fadeOut();
history.pushState({}, 'Title', '/Url/Test');
$(document).load('/url html', function () {
$('body').fadeIn();
});
});
You may also add a JavaScript "fadeout" animation when "unloading" the current page, and a "fadein" animation executing at the begining of the next page load.
If you prefetch most of your content, the transition will be smooth.
To avoid a page load when you click on a link, attach an onclick event to your link, and finish your JavaScript callback by a e.preventDefault(); as explained in this question : How to stop default link click behavior with jQuery from Mozilla Dev Network : https://developer.mozilla.org/en-US/docs/Web/API/event.preventDefault
Cancels the event if it is cancelable, without stopping further propagation of the event.
About link prefetching : https://developer.mozilla.org/en-US/docs/Web/HTTP/Link_prefetching_FAQ
<link rel="prefetch" href="/images/big.jpeg">
Or even really loading <img with a style=display:none; to hide them…
I want to refresh the current page when clicking browser back button, it refreshes the same page but the page is refreshed even when I click logout button in the same page. Please give me valuable solution. Thanks in advance
window.addEventListener('popstate', function (event) {
if (window.event) {
location.reload(true);
}
}
Friend you can not play with the browser function to go back. But you can add in the function of close session the following code
location.reload();
You can also place an event that triggers the same function that will reload the page
And if you want to redirect to another url you can use the following code
window.location.replace("http//:URL.COM");
i got a problem with a connection between two html files with a *.js
i got index.html i got a formular.php and i got a backbutton.js
what i want to do is: if i send my fomular via button im calling the formular.php to write the text into my MySQL database. If someone forgets to put in an e-mail adress i got a error page which got a button "back". with that button i want to get back to the formular page.
My Problem is that my index.html is a page with 3 differt divs with the ids page1, page2, page3. when the user finishes a quiz the page changes itself from page1 to page2 with a
function checkplayer() {
if (player1 == true && player2 == true && player3 == true && player4 == true) {
setTimeout(function() {
$(document).ready(function() {
$("#page1").fadeOut(1000);
setTimeout(function() {
$("#page2").fadeIn(1000);
}, 1500);
});
}, 1000);
}
so my whole page is 1 page at all with 3 differnt divs that are faded in and out.
If i use my back button from the formular.html with history.back(); i land at the page1 div. But i need to get to the page3 div with the formular. Same happens if i reload my page. i always land on page1 since my index.html starts with page1 and page2 and page3 are set to display: none. Thats why i guess the history back is not working in this case since i step back always means a new loaded index.html
What i tried is to make a backbutton.js
function backButton() {
jQuery("#errorpage").fadeOut(0);
jQuery("#page3").fadeIn(0);
}
The errorpage is faded out but the page3 is not faded in because the backbutton.js doesnt know the index.html in which the page3 div is.
Is there any possiblity to get the errorpage to fadeout and the index.html page3 to fade in? is it possible to "import" the index.html page3 div into the backbutton.js?
Anyone got an Idea on how to get a connection between these 3 files or if there is any other way to get the errorpage to fadeout and my page3 div to fadein?
Any help is appreciated. Thank you
You can pass the hash to a URL:
function backButton() {
jQuery("#errorpage").fadeOut(0);
window.location = "index.html#page3";
}
and then check for the same hash on original page like this:
function checkHash() {
$(document).ready(function() {
if (window.location.hash === "#page3") {
$("#page3").fadeIn(1000);
}
});
}
Also, consider not allowing user to go forward at first place, if e-mail address is not entered.
Consider using the hash (#) to identify the 3 different pages; i.e. when switching from page 1 to page 2 signal it by changing your URl to 'YOUR_PHP_PAGE.php#page2' etc. This way, the browsers history (as well as re-load) should be able to correctly handle it. In the page-JS listen to the hash-changed-event and show the appropriate div. (Note that changing the hash by location.href = ...#page2 does NOT re-load the page, but triggers the event.)
Regarding the error page (fade in/out) you could place it on the same page. Then use ajax to post the data back to the server instead of loading a new page..
You can use hash term as id in div and wee can call by adding hash like this (index.html#page2) to land on the specific div. This directly lands to the id instead of reload the whole page. Same time we can use fade in fade out using jquery and ajax script to post the data
It has been common to direct the user using anchors. With HTML5 you can make use of the history / state APIs through History.js.
I rewrote your code using the history.js plugin. Read the comments within the sample code to see what is happening. Replace the page2finished() and throw_error() functions with your currently existing ways of telling when the user has finished page 2 and when an error should be shown. Those were included to show you the flow this code should take.
HTML
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/history.js"></script>
JavaScript
$(document).ready( function() {
var player1,
player2,
player3,
player4,
errorpage = $("#errorpage");
//Initialize the history.js script by binding it to the window object.
History.Adapter.bind(window,'statechange',function(){
var State = History.getState();
});
//Add page 1 to the browser history and load the first anchor.
History.pushState({state:1}, "Page 1", "?page=1");
//Make sure that the other elements are hidden when the user first loads the page.
$("#page2, #page3, #errorpage").hide();
function checkplayer() {
if (player1 && player2 && player3 && player4) {
$("#page1").fadeOut(1000, function() {
$("#page2").fadeIn(1000, function() {
//Add page 2 to the browser history and load the second anchor.
History.pushState({state:2}, "Page 2", "?page=2");
});
});
}
}
//After the user is done with page 2 throw them to page 3 by adding it to the browser history then loading the third anchor.
function page2finished() {
$("#page2").fadeOut(1000, function() {
//Add page 3 to the browser history and load the third anchor.
$("#page3").fadeIn(1000, function() {
History.pushState({state:3}, "Page 3", "?page=3");
});
});
}
//Something went wrong! Show the #errorpage element.
function throw_error(text) {
//Put the error text into the element and show it to the user.
errorpage.text(text);
//Hide the main pages.
$("#page1, #page2, #page3").hide();
//Add the error to the browser history and show that anchor.
errorpage.show();
History.pushState({state:3}, "Error", "?page=errorpage");
}
//The user clicked the back button
function backButton() {
errorpage.hide();
//We saved '3' linking to page 3 so tell history.js to go there.
History.back(3);
}
});
I have 4 pages within my JQM main HTML file. When I switch to one using changepage it's fine the first time, but I use a data-rel=back button to go back and this switches to the previous page but then bounces back to the page that has the back button. Should I just not use data-rel=back? If not what alternative is there?
Using JQM 1.3.1
$("#listView").on("vclick","li", function(e) {
//ajax call to get results for second page
$.mobile.changePage('#second');
}
Button on second page
Back
To go to previous page programmatically, use the below code. You need also to use stopImmediatePropagation(); to stop jQuery Mobile from jumping twice, which will result showing the same page.
Edit: I tested it on iPad, preventDefault() is required too.
Demo
$(document).on('vclick', '[data-rel=back]', function (e) {
e.stopImmediatePropagation();
e.preventDefault();
var back = $.mobile.activePage.prev('[data-role=page]');
$.mobile.changePage(back, {
transition: 'slide',
reverse: true });
});
Use this one. You can redirect between pages using location.hash=" " with page id in it.
DEMO http://jsfiddle.net/yeyene/uJz3E/7/
$("#listView").on("vclick","li", function(e) {
// second is the page you want to redirect on click.
location.hash = "second";
});