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.
Related
I have the following code which works exactly as I need for refreshing a page using a submit button.
However I have added code in it to make it scroll down to a specific location after updating, the problem is, it scrolls down to the location, then springs back to the top of the page
any ideas why anybody please?
$(".visitpage").on('click', function() {
$('body').append('<div style="" id="loadingDiv"><div class="loader"></div><center><span style="font-size:22px;color:#000000;z-index:99999;"><b>Updating your results...</b></span></center></div>');
setTimeout(removeLoader, 2000); //wait for page load PLUS two seconds.
$('html, body').animate({
scrollTop: $("#search-results").offset().top
}, 2000);
});
function removeLoader() {
$("#loadingDiv").fadeOut(500, function() {
// fadeOut complete. Remove the loading div
$("#loadingDiv").remove(); //makes page more lightweight
});
}
You will surely need the scrollTo method of the window object in javascript. Then I would figure out how far down your element is by getting a reference for that object in pixels on the page. See Retrieve the position (X,Y) of an HTML element for how to do that, since part of your answer would be a duplicate question I will let you read it. And this article is helpful http://javascript.info/coordinates
window.scrollTo(500, 0);
https://www.w3schools.com/jsref/met_win_scrollto.asp
Maybe I'm wrong here; but if you created a div where you want the page to scroll, or if you have on there make sure it's named, then right after the refresh command add
window.location.href = "#YOURDIVTAGHERE"; so
So if this is the part of the page you want it to go down to:
<div id="search-results">
CONTENT
</div>
so then your JS code, maybe try:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
$(".visitpage").on('click', function(){
$('body').append('<div style="" id="loadingDiv"><div class="loader"></div><center><span style="font-size:22px;color:#000000;z-index:99999;"><b>Updating your results...</b></span></center></div>');
setTimeout(removeLoader, 2000); //wait for page load PLUS two seconds.
});
function removeLoader(){
$( "#loadingDiv" ).fadeOut(500, function() {
// fadeOut complete. Remove the loading div
$( "#loadingDiv" ).remove(); //makes page more lightweight
});
window.location.href = "#search-results";
}
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);
});
I am trying to implement an infinite scroll pagination with javascript in jsfiddle but i am having issues getting it to work properly. I am not seeing the fading in when scrolling and when i reach the end of the content i am supposed to get the message that there is no more data but instead it says it is waiting for more data.
The original example: http://andersonferminiano.com/jqueryscrollpagination/
My implementation: http://jsfiddle.net/jsuHD/
I added an External Resource to the jsfiddle: scrollpagination.js
I think my problem is with the javascript and not knowing what to pass in as contentPage
$(function(){
$('#content').scrollPagination({
'contentPage': 'http://jsfiddle.net/jsuHD/', // the url you are fetching the results
'contentData': {}, // these are the variables you can pass to the request, for example: children().size() to know which page you are
'scrollTarget': $(window), // who gonna scroll? in this example, the full window
'heightOffset': 10, // it gonna request when scroll is 10 pixels before the page ends
'beforeLoad': function(){ // before load function, you can display a preloader div
$('#loading').fadeIn();
},
'afterLoad': function(elementsLoaded){ // after loading content, you can use this function to animate your new elements
$('#loading').fadeOut();
var i = 0;
$(elementsLoaded).fadeInWithDelay();
if ($('#content').children().size() > 100){ // if more than 100 results already loaded, then stop pagination (only for testing)
$('#nomoreresults').fadeIn();
$('#content').stopScrollPagination();
}
}
});
// code for fade in element by element
$.fn.fadeInWithDelay = function(){
var delay = 0;
return this.each(function(){
$(this).delay(delay).animate({opacity:1}, 200);
delay += 100;
});
};
});
If you fire up the console [f12 in google chrome] you will see that when you reach the end of the page a 403 forbidden request is made to jsFiddle itself. Yes I think the problem is in what you are passing to contentPage.
Here's a working fiddle http://jsfiddle.net/jsuHD/10/ of your solution. When you load the html from an external source which allows you to get the resource you want, it works as expected.
//load the html from external resource
'contentPage': 'http://dl.dropbox.com/u/4001846/sample.html'
UPDATE:
I was able to get my scroller working as desired but I feel like I have hacked around the actual issue and would love it if anyone has a more solid answer, I've updated and noted in the snippets below the new jQuery I'm using.
I'm using iScroll-4 (http://cubiq.org/iscroll-4) for an iPad/Android web app, everything's working perfectly with the swipes and scrolling but I have a table of contents at the beginning of the app that allows users to jump to specific areas of the scroller --
I'm using the iScroll function scrollToElement(element, duration) in order to jump to the different areas. Also using scrollToPage(page, duration) to allow the user to manually navigate forward and backward one page at a time.
While watching the console logs the currPageX variable updates when I navigate with the scrollToPage function and when I swipe, but when using the scrollToElement the currPageX variable does not update.
Therefore if I jump to an element and then navigate forward with scrollToPage('next', 0) it will go backwards and navigate me to the next page after the table of contents.
I have tried using the scroll.refresh() function after scrollToElement, before, putting the function inside a timeout, etc. and I can't figure out why the currPageX is not updating.
Here's a snippet of the jQuery code that I'm using the two different functions:
// TO NAVIGATE FORWARD AND BACKWARDS
$('span.control').on('click', function() {
var slideDir = $(this).attr('data-dir');
if (slideDir == 'prev') {
var tehPg = tehScroll.currPageX-1;
} else if (slideDir == 'next') {
var tehPg = tehScroll.currPageX+1;
}
tehScroll.scrollToPage(tehPg, 0);
return false;
});
// TO JUMP FROM CONTENTS
$('li[data-page="toc"] span').on('click', function() {
var toPage = $(this).attr('data-page');
tehScroll.scrollToElement('li[data-page="'+toPage+'"]', 800);
// ADDED THE FOLLOWING LINE TO MANUALLY SET currPageX after scrolling!
tehScroll.currPageX = $('#slides li[data-page="'+toPage+'"]').index();
return false;
});
Did you consider using jquery-mobile-iscrollview widget plug-in? - there is a function scrollToPage(pageX, pageY, time), works well for me...
best
M
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.