I'm using Jquery.Localscroll to move the window smoothly between anchors. How would you change the URL when the page loads to include an anchor link so it scrolls smoothly to a section when the page loads.
Or is there a better way to scroll to a section when the document loads.
Thanks.
Obviously if you specify the anchor to scroll to in the tradional way:
Link
Then the browser will scroll automatically.
If your intention is for the browser to load the page and then have your code kick in to do a smooth (animated) scroll to a particular anchor then something like this would work:
// on calling page
Link
// on "yourURL" page:
$(document).ready(function() {
// check for "scrollto" parameter and if it exists
// use Localscroll to move to specified anchor
var match = /[?&]scrollto(?:=([^&]*))?/.exec(window.location.search);
if( match != null ){
var anchor = match[1];
// your code to scroll to anchor here
}
});
Related
I'm wanting to link to a certain tab (Portfolio Tab) on a page from the main menu of a website, so when clicked it goes to that page with that portfolio tab open.
So far I've come up with this (using jQuery Tabslet) which works when not on the same page, but doesn't work if the user happens to be on the same page as the tabs, and so does nothing.
The link I use in the main menu is /about/#tab-3 which is doing the job of going to the about page with the portfolio tab open.
I thought I may need to trigger a page refresh when on the same page? And perhaps remove the #tab-3 from the url too.
Not being a jQuery expert, I unfortunately just don't know.
Here is the code so far
Thanks in advance.
jQuery(document).ready(function($){
$('.tabs').tabslet({
active :1,
animation : true,
container: '.tabs-container'
});
var hash = $.trim( window.location.hash );
var anchor = $('a[href$="'+hash+'"]');
if (anchor.length > 0){
anchor.click();
}
window.onload = function () {
if (location.hash) {
window.scrollTo(0, 0);
}
};
});
Advise: Always mention a reference to the plugin you use. I assume here you talk about this one.
This plugin acts on tab click only.
So when using a window hash in a link from another page like you do, you have to "simulate" a click on the tab.
So you will use an attribute selector to find the anchor having a href corresponding to the hash...
And click it.
window.onload = function () {
if (location.hash) {
window.scrollTo(0, 0);
$("a[href='"+location.hash+"']").click(); // Add this!
}
};
Is it possible to take a user back to the area of a page where they scrolled down to when pressing the back button in a browser? As in --- pageA is double your screen size (hence you have to scroll to read more). You click a link on pageA to go to a new page - pageB. After reading you click back in browser. Now when you return to pageA you are back at the top and have to scroll down to where you were to continue reading the rest of the page.
Is there a Jquery or JS way to return to that point in the page. Maybe something with .scrollTop()?
If the content is loaded after page "load" event firing, then the back button would not take you back to the position you were. Because the browser scrolls before the 'load' event.
To make the browser remember the scroll position in this case, you have to store the scroll position and status (what content have been loaded) somewhere before navigating away. Either in the cookie, or in the url hash.
If pageA is just a static page without dynamic content (loaded after 'load' event, the browser should remember the scroll position when you go back.
For dynamic content, there at least includes two parts. One is recovering the page status when click "Back" button, so all the dynamic content is loaded, some expander are expanded or collapsed. The other is scroll to there.
The first part depends on how the page is implemented. The 2nd part you can put the scroll top into the cookie when page doing onUnload. For example
$(window).unload(function() {$.cookie('scrollTop',$(window).scrollTop());});
You can do this by using session storage.
$(window).scroll(function () {
//set scroll position in session storage
sessionStorage.scrollPos = $(window).scrollTop();
});
var init = function () {
//return scroll position in session storage
$(window).scrollTop(sessionStorage.scrollPos || 0)
};
window.onload = init;
You can use the following code to detect the scroll position.
$(window).scroll(function (event){
var scroll = $(window).scrollTop();
// Do something
});
Then store scroll in a session and when you click back do scrollTop(scroll) .
This should definitely be done using the History API since it is the only way of knowing for sure that the user went back to the page using the back button of the browser.
First of all, you want to prevent the default scroll restoration of the browser in order to handle it yourself. See this article for details.
if ('scrollRestoration' in history) history.scrollRestoration = 'manual'
Then you need to store the scroll position in the history.state when the user leaves the page. This can be done on beforeunload using history.replaceState.
window.addEventListener('beforeunload', storeScrollPositionInHistoryState)
function storeScrollPositionInHistoryState() {
// Make sure to add lastScrollPosition to the current state
// to avoid removing other properties
const newState = { ...history.state, lastScrollPosition: scrollY }
// Pass the current location.href since you only want to update
// the state, not the url
history.replaceState(newState, '', location.href)
}
or with ES5
function storeScrollPositionInHistoryState() {
var newState = Object.assign({}, history.state, { lastScrollPosition: scrollY })
history.replaceState(newState, '', location.href)
}
Finally, whenever your page is ready to scroll back to its previous position, you check if history.state.lastScrollPosition is defined and if it is the case, you restore the scroll position and remove it from the history.state.
function restoreLastScrollPositionIfAny() {
if (typeof history.state.lastScrollPosition !== 'number') return
scrollTo(scrollX, history.state.lastScrollPosition)
const cleanState = { ...history.state }
delete cleanState.lastScrollPosition
history.replaceState(cleanState, '', location.href)
}
There are still one edge case that is not covered:
The user might have resized the window after leaving the page which can result in an incorrect scroll position when going back to the page. Developers resize the window very often, but real users not that much. That's why I consider it as an edge case.
One way to solve it could be to also store the window size in the history.state and avoid restoring the scroll position if the current window size doesn't match the one stored in the state.
Hope it helps.
After trying #bowen option I have arrived to a better one with smooth scroll and without the problem said by #Frits
$(window).scroll(function () {
//set scroll position in session storage
if ($(window).scrollTop() > 500)
sessionStorage.scrollPos = $(window).scrollTop();
});
var init = setTimeout(function(){
//return scroll position in session storage
if (sessionStorage.scrollPos > 500){
$("html").animate({ scrollTop: sessionStorage.scrollPos },2000);
}
},1000);
window.onload = init;
//For Angular
//Save your scroll position once you scroll
#HostListener('window:scroll', ['$event']) onScrollEvent($event){
sessionStorage.scrollPos = window.scrollY
}
//Scroll to the save value postion
ngAfterViewInit(){
window.scrollTo(0, sessionStorage.scrollPos)
}
I use Fancybox to display external html pages in fancybox, for example : In page1 I set a link, which opens page2 in fancybox iframe mode, and that works fine.
The question is :
Is it possible that if somebody tries to enter the URL of page2, make page2 to always open in fancybox from within page1 instead of the browser window like a normal page?
Yes, it's possible.
So page one (parent.html), will open page two (iframed.html) in fancybox from a link like
<a id="openIframe" class="fancybox" href="iframed.html">Open page inside fancybox iframe</a>
Notice that I set an ID and a class to the link that will open the iframed page.
Then the script for each page:
parent.html
parent page should have two specific codes :
a code to initialize fancybox
a code to detect when a hash is present in the URL so it can fire fancybox
so :
// initialize fancybox
$(".fancybox").fancybox({
// API options
type: "iframe" //<== at least this one
});
if (window.location.hash) {
// detect if URL has hash and trigger fancybox
$(window.location.hash + ".fancybox").trigger("click");
// remove hash after fancybox was opened
// two methods to cover most browsers
if (navigator.userAgent.match(/msie/i)) {
var loc = window.location.href;
index = loc.indexOf('#');
if (index > 0) {
window.location = loc.substring(0, index);
}
} else {
history.pushState("", document.title, window.location.pathname);
};
};
Then the second page (iframed.html) should have a code that detects if itself has been opened inside an iframe or not (the fancybox iframe in our case).
If not, it should redirect to the parent page, targeting the ID of the link that opens fancybox so :
iframed.html
if (self == top) {
window.location.href = "parent.html#openIframe";
};
Notice that self == top will return true if the page wasn't opened inside an iframe so it redirects to parent.
See JSFIDDLE (and try also opening the link in a new window/tab)
I have html page(parent page) that contains a iframe(child page inside this iframe),
this java script function get the location where i want to scroll iframe using internal page linking.
function scrollToAnchor ()
{ //function parseParameter return the query string value from the url
var anchor = parseParameter(window.location.href,'anchor');
if (anchor != null)
{
location.hash=anchor;
}
}
but anchor value in iframe page source not in parant page,
this is not able to scroll the iframe page.how to scroll iframe page through parant page,
it works in IE and Crome but doesn't work in firefox. there is any alternative of this code.please suggest.
my parant page url is
http://localhost:8989/schoolforms/SelectForm?formTypeID=STUDENT_EMERGENCY
This is my window.location.href" value that is for iframe
http://localhost:8088/schoolforms/StudentEmergency?student=B874BCC3EA5B83670988C959E9F0036B&anchor=InsuranceInfo
after parsing anchor contains InsuranceInfo after this function url becomes like
http://localhost:8088/schoolforms/StudentEmergency?student=B874BCC3EA5B83670988C959E9F0036B&anchor=InsuranceInfo#InsuranceInfo
JQuery bbq has a nice 'deparam' function
https://github.com/cowboy/jquery-bbq/
var params = $.deparam.querystring();
window.location.hash = params['anchor']
Too many missing information to understand what exacly do you want to achieve. I guess that you need to scroll your page to the anchor with id from anchor variable of window.location.href.
I don't know how works your function parseParameter() and I need to believe that is working good.
location.hash contains the part of URL after # for example #news etc. So if you pass a string to location.hash browser will add this string to URL and scroll to the html element with the same ID.
EFFECT
http://localhost:8088/schoolforms/StudentEmergency?student=B874BCC3EA5B83670988C959E9F0036B&anchor=InsuranceInfo#InsuranceInfo
It's not a good way, because after that you will have both anchor variable and hash in your URL.
TRY THIS
function scrollToAnchor ()
{
var anchor = parseParameter(window.location.href,'anchor');
if (anchor != null)
{
$('html, body').animate({scrollTop: $('#'+anchor).offset().top}, 0);
}
}
I used .animate() because if you want you can change in this line 0 to for example default value, which is 400 (i guess ms unit) and it will scroll with animation (delay). If you leave 0 it will scroll to the element immediately without any delay.
$('html, body').animate({scrollTop: $('#'+anchor).offset().top}, 400);
I have a page http://bartle96.narod2.ru/demo.html there are 4 links to the hidden content
Is it possible to make a direct link to the content such as "dolphin".
So that when you click on a link http://bartle96.narod2.ru/demo.html#delfin immediately opened a photo with a dolphin
Yes, you can define and open needed content on onload event.
Check this post where you can find the same behaviour:
jQuery when pointed to a link should show a div that's hidden by default
You can get the hash value using window.location.hash. Then set the pic you want based on the value.
window.onload = function() {
var pic = window.location.hash;
if ( pic === "#delfin" ) {
// Show picture of dolphin
}
}