Using jQuery-Smooth-Scroll from one page to another? - javascript

I am currently using jQuery-Smooth-Scroll to smoothly scroll up and down to various anchor positions on one of my pages (Page 1). However, what I would also like to be able to do is, from another page (Page 2), link to Page1 (appending #bookmark to the url) and have jQuery-Smooth-Scroll pick up on the fact I am calling the page with a #bookmark and have it smoothly scroll down to the relevant position once the page has completed loading. I don't know if this is a possibility or not?
This is the version of Smooth-Scroll that I'm using:
https://github.com/kswedberg/jquery-smooth-scroll
I'm still relatively new to jQuery so I may be overlooking something obvious.

Ajma's answer should be sufficient, but for completeness:
alert(location.hash)
Edit: a more complete example:
// on document.ready {
if (location.hash != '') {
var a = $("a[name=" + location.hash.substring(1) + "]");
// note that according to w3c specs, the url hash can also refer to the id
// of an element. if so, the above statement becomes
// var a = $(location.hash);
if (a.length) {
$('html,body').animate({
scrollTop: $(a).offset().top
}, 'slow');
}
}
// }

It's possible, you want to put a call into the smooth scroll function when the page is finished loading. in jQuery, it's using $(document).ready(function () { your code } );
You'll need to put something in to parse your url to extract the #bookmark and then call the smooth scroll.

Related

jQuery history usage

I have created a webpage that uses jQuery to show and hide elements. The obvious problem now arose; the back and forward browser buttons don't work anymore as everything is loaded within a single location.
I know the answer lies within jQuery History but after busting my head for several hours on their website and examples given here on stackoverflow, I still cant manage to:
A) create a history entry (I think i got this covered but not 100% sure)
B) animate the page transition with my own function (displayed beneath)
This is the website: www.grommit.nl
There are 4 sub-pages that require a history entry when called upon.
This code shows the transition of the "wordpress page". The other pages work in a similiar way. (so far I have only managed to generalize the last part of the pageload with the "LoadPageContent" function, the bit before that is different with every page)
var LoadPageContent = function() {
$(".sceneBody").slideDown(function() {
$(".aftertitle").css('width', '4em');
$(".mediacontainer").fadeTo('0.3s', 1,)
});
$("#goWordpress").click(function () {
$("#homeScene").fadeOut(function () {
$("#wordpressMessage").fadeIn(function() {
$(this).delay(300).slideUp(function() {
$("#wordpressPage, #grommitFixed").slideDown(function() {
LoadPageContent();
});
});
});
});
});
this is the function that is currently working as a previous button within the DOM. I would like this function to execute when the previous button is clicked.
var goBack = function() {
$(".aftertitle").css('width', '0em')
$(".mediacontainer").fadeTo('0.3s', 0, function() {
$(".scenebody, #grommitFixed").slideUp(function() {
$("*[id*=Page]:visible").each(function() {
$(this).slideUp(function() {
$("#homeScene").fadeIn();
});
});
});
});
};
In html5 you have something called pushstate, that you can use to tell the browser what to go back to. Check out:
html pushstate

Scrolling works only after refreshing the page

On my first page I have some buttons (promo1, promo2, promo3,...) who respectively lead to the element with the id "promo1" or "promo2" or "promo3",... on the second page.
So when I land to the second page I want to scroll directly to the element I choosed with the button. So I pass the id like that:
mysite.com/secondpage/:promo1(/2/3, depends on the button.)
and I get the id by using $routeParams from angularJs.
But I have a really huge problem: the scroll stop on middle of the page (maybe because it stop when the element is viewable on screen, let me know), but if I refresh the page, the scroll do what I ask for and stop on top on the element!
Here is the code I use at the moment:
$scope.goToAnchor = function(){
// This is just one of the test I've made, does not work better.
// if ($routeParams.anchor == ':promoFamily' || $routeParams.anchor == ':promoGroup' || $routeParams.anchor == ':promoCard'){
// $scope.anchor = $routeParams.anchor.replace(':','#');
// $('html, body').animate({
// scrollTop: $($scope.anchor).offset().top
// }, 200);
// }
// Code I use:
if ($routeParams.anchor == ':promoFamily' || $routeParams.anchor == ':promoGroup' || $routeParams.anchor == ':promoCard'){
$location.hash("#");
$location.hash($routeParams.anchor.replace(':',''));
$anchorScroll();
}
};
$scope.goToAnchor();
Event if you have only some hints, be free to leave a comment, it will help me as long as i'am working on this for 2 days now...
This is because your elements are not fully loaded when your goToAnchor function is being called.
Use $timeout to call $scope.goToAnchor() after 1 second(change it according to your page load time).
First, inject $timeout in your controller.
Then,
$timeout(function() {
$scope.goToAnchor();
}, 1000);
Inject $timeout in your controller, and use it like below.
$timeout(function() {
$scope.goToAnchor();
});
This will help calling the function after rendering the full view.

jQuery OnLoad Page Scroll Issue

I'm developing a website which involves the user being able to navigate to different parts of a page from other pages using # values in the address bar.
I have written a jQuery function to handle the scrolling here:
jQuery.fn.scrollToDiv = function(navheight)
{
if (!navheight)
{
navheight = 30;
}
var offset = this.offset();
var offsetTop = offset.top;
var totalScroll = offsetTop-navheight-27;
$('body,html').animate({
scrollTop: totalScroll
}, 500);
}
And I am calling the function in 2 different scenarios; when the user clicks a link where the object is on the current page, and when the user clicks a link that takes them to another page before scrolling to the element. See below:
When you are on the page:
$('.gotoPage').on('click', function(e)
{
e.preventDefault();
var sPath = window.location.pathname;
var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
if (sPath != '' && sPath != 'home')
{
var href = $(this).attr('href');
handleScroll(href);
}
});
and when you are not on the page:
$(document).ready(function(e)
{
var target = window.location.hash;
if (target != '')
{
$(target).scrollToDiv(30);
}
});
It works perfectly when you are on the page and click the link, however when you're not on the page, it takes you to the subsequent page as you'd expect but it doesn't then scroll to the required element.
Let me know if you need any more information
Thanks in advance
EDIT: Added function handleScroll(target)
function handleScroll(target)
{
if (target != '')
{
$(target).scrollToDiv(30);
}
}
Following your comment:
I've noticed when refreshing the page is that it scrolls down then
jumps back to the top of the page
It seems that your script does work, but something affecting it afterwards.
I believe that there are some resources as additional css codes or images that aren't being taken in account when the scroll animation takes effect and since that function works by top offset - you must be sure that you're using it after all the resources that might affect the document's height or element's offset, are being loaded.
Therefore, instead of using your script in .ready(), use .load().
.ready() vs. .load()
In most cases, the script can be run as soon as the DOM hierarchy has
been fully constructed. The handler passed to .ready() is guaranteed
to be executed after the DOM is ready, so this is usually the best
place to attach all other event handlers and run other jQuery code.
In cases where code relies on loaded assets (for example, if the
dimensions of an image are required), the code should be placed in a
handler for the load event instead.

Change location.hash on unbeforeunload

I have a page which is generated using JavaScript. I want to store the $(window).scrollTop() value in a hash (like #position=xxx) so when the page is refreshed and the items are generated again, the user can continue scrolling from where they left off.
I'm trying to modify the hash on beforeunload, which does not seem to work. The first part of the function below tries to change the hash, and the second part is taking care of the modification of the scrollTop on page load. The second part works fine, I'm only stuck with the first part.
$(window).on('beforeunload',function(){
window.location.hash = "position="+$(window).scrollTop();
}).on('load hashchange',function(){
var scrollregex = /^position=(\d+)$/,
hash = window.location.hash.substring(1);
if (scrollregex.test(hash)) $(window).scrollTop(parseInt(hash.match(scrollregex)[1]));
});
Is there a different event for this, or otherwise how can I change the hash when the user triggers a refresh?
I ended up ditching the hash idea and going with a sessionStorage based approach. I wrote my own wrapper for session/local storage which I use in the following example.
$(window).on('beforeunload',function(){
var scrltop = $(window).scrollTop();
if (scrltop > 0) SStorage.set('position',scrltop);
else SStorage.del('position');
}).on('load',function(){
if (SStorage.has('position')){
var pos = parseInt(SStorage.get('position'));
if (!isNaN(pos) && $(window).scrollTop() === 0) $(window).scrollTop(pos);
}
});
Chrome doesn't seem to allow you to update the hash in the onbeforeunload event. I had a similar issue. I moved my code to the unload event, which worked but introduced other issues. To solve them I have to force a reload, note reload will not work without the setTimeout.
$(window).on('unload', function(){
/* Do hash change here */
setTimeout(function () { window.location.reload(true); }, 0);
});

jQuery: how to scroll to certain anchor/div on page load?

Lately im trying to use jquery more often and right now im having some problem i'd like to solve with jquery hope u could help me.
I have some web page that includes some anchor tag (lets say the anchor is located in the middle of the page) and on the event onload i want the page to start on that certain anchor tag location meaning the page will be "scrolled" automaticaly to a certain location.
That was my previous solution (which is quite ugly since it adds #i to my url)
window.onload = window.location.hash = 'i';
Anyway could u tell me how can i do it with jquery?
notice: i don't want the user to feel any slide or effect while getting to this location
Use the following simple example
function scrollToElement(ele) {
$(window).scrollTop(ele.offset().top).scrollLeft(ele.offset().left);
}
where ele is your element (jQuery) .. for example : scrollToElement($('#myid'));
There's no need to use jQuery because this is native JavaScript functionality
element.scrollIntoView()
I have tried some hours now and the easiest way to stop browsers to jump to the anchor instead of scrolling to it is: Using another anchor (an id you do not use on the site). So instead of linking to "http://#YourActualID" you link to "http://#NoIDonYourSite". Poof, browsers won’t jump anymore.
Then just check if an anchor is set (with the script provided below, that is pulled out of the other thread!). And set your actual id you want to scroll to.
$(document).ready(function(){
$(window).load(function(){
// Remove the # from the hash, as different browsers may or may not include it
var hash = location.hash.replace('#','');
if(hash != ''){
// Clear the hash in the URL
// location.hash = ''; // delete front "//" if you want to change the address bar
$('html, body').animate({ scrollTop: $('#YourIDtoScrollTo').offset().top}, 1000);
}
});
});
See https://lightningsoul.com/media/article/coding/30/YOUTUBE-SOCKREAD-SCRIPT-FOR-MIRC#content for a working example.
i achieve it like this..
if(location.pathname == '/registration')
{
$('html, body').animate({ scrollTop: $('#registration').offset().top - 40}, 1000);
}
Have a look at this
Appending the #value into the address is default behaviour that browsers such as IE use to identify named anchor positions on the page, seeing this comes from Netscape.
You can intercept it and remove it, read this article.
/* START --- scroll till anchor */
(function($) {
$.fn.goTo = function() {
var top_menu_height=$('#div_menu_header').height() + 5 ;
//alert ( 'top_menu_height is:' + top_menu_height );
$('html, body').animate({
scrollTop: (-1)*top_menu_height + $(this).offset().top + 'px'
}, 500);
return this; // for chaining...
}
})(jQuery);
$(document).ready(function(){
var url = document.URL, idx = url.indexOf("#") ;
var hash = idx != -1 ? url.substring(idx+1) : "";
$(window).load(function(){
// Remove the # from the hash, as different browsers may or may not include it
var anchor_to_scroll_to = location.hash.replace('#','');
if ( anchor_to_scroll_to != '' ) {
anchor_to_scroll_to = '#' + anchor_to_scroll_to ;
$(anchor_to_scroll_to).goTo();
}
});
});
/* STOP --- scroll till anchror */
just use scrollTo plugin
$("document").ready(function(){
$(window).scrollTo("#div")
})
Just append #[id of the div you want to scroll to] to your page url. For example, if I wanted to scroll to the copyright section of this stackoverflow question, the URL would change from
http://stackoverflow.com/questions/9757625/jquery-how-to-scroll-to-certain-anchor-div-on-page-load
to
http://stackoverflow.com/questions/9757625/jquery-how-to-scroll-to-certain-anchor-div-on-page-load#copyright
notice the #copyright at the end of the URL.

Categories