HTML smooth scrolling[without anchor animation]? - javascript

Would it be possible to create a smoother scrolling for a webpage?
For example MS Word 2013 has the kind of scrolling effect,
I'm searching for.
Haven't found any other examples yet.
I've heard that you can do pretty much that kind of stuff with AJAX, so would it be possible with that?
I don't want a smooth scroll to anchor, but when you scroll down the page freely with your mouse wheel or the scroll bar. But I'm searching for a similar effect to this ''smooth scroll to anchor''.

NiceScroll is what I was looking for.
It makes the scroll much smoother, as I wanted.
https://code.google.com/p/jquery-nicescroll/downloads/detail?name=jquery.nicescroll.350beta5.7z&can=2&q=

No. Scroll speed is determined by the browser (and usually directly by the settings on the computer/device). CSS and Javascript don't (or shouldn't) have any way to affect system settings.
You can try to fake it but the look and feel of the scroll bar would be compromised.
If and only if you capture the scroll events, then you would be able to adjust your content dynamically so that the portion you want is visible.
Flash might give you some liberty in acheiving your goal.
[EDIT]
PLEASE DO NOTE:THIS IS WITHOUT ANCHOR TAG
I tried to simulate a your query without any anchor tag.Although it's not perfectly answers to your question,it's still worth a shot:-
HTML:-
<div id="div1">asdf1</div>
<div id="div2">asdf2</div>
<div id="div3">asdf3</div>
<div id="div4">asdf4</div>
<div id="div5">asdf5</div>
<div id="div6">asdf6</div>
<div id="div7">asdf7</div>
<div id="div8">asdf8</div>
<div id="div9">asdf9</div>
<div id="div10">asdf10</div>
CSS:-
div {
height: 50px;
}
And finally add this to your jquery:-
$(document).ready(function () {
$("html, body").animate({
scrollTop: $("#div5").offset().top
}, 5000);
});

You can do it easily with JQuery
Load JQuery
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<script>
$(function() {
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
});
</script>
The above code will work perfect for the smooth scrolling

Related

jQuery scroll with animate does not scroll to the correct location

My goal is to have my page scroll to a specific div if a user has visited the page before. I am using the following code:
$('html, body').animate({
scrollTop: $("#userResults").offset().top - 72
}, 1000, "easeInOutExpo"
);
#userResults is the appropriate target div. The problem is, when the page loads, it scrolls to roughly the middle of the page. I've tried rearranging the divs out of the fear that one div that contained canvas elements was throwing things off, but that didn't work. I tried hardcoding a scroll value; I tried retrieving the page height and div heights to force a scroll position, but none of that worked. Further, when I test against different screen sizes, the scroll goes to different points around the middle of the page.
What is the most frustrating is that when I click on links on the loaded page that target divs, they go to the exact location. Those use the following code:
$('a.js-scroll-trigger[href*="#"]:not([href="#"])').click(function() {
if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
if (target.length) {
$('html, body').animate({
scrollTop: (target.offset().top - 72)
}, 1000, "easeInOutExpo");
return false;
}
}
});
That last block of code comes from the template that I'm building from, which comes from: https://startbootstrap.com/themes/creative
Here's a codepen of the relevant code: codepen The specific code block can be found around line 99 of the javascript. Also, the codepen doesn't demonstrate the problem behavior, probably because it doesn't allow me to create variables in local storage.
I've been coding for about a year, so I'm no expert and may need a little handholding. How do I get this thing to scroll to the right position on load?

How to scroll the page smoothly?

I need to scroll the page on load to a certain position on the page in an animated manner. And it works fine (using jQuery's animate):
$(document).ready(function () {
$('html, body').animate({
scrollTop: $('#today').offset().top - 50
}, 800, "linear");
});
However, one thing that it is not is smooth. Particularly on a mobile device it feels very jerky.
I've seen some CSS animations (using transition and transform) that are very smooth but can't figure out how to apply it to page scrolling. Is it possible to do what I want using CSS?
Try setting the following css:
<style type="text/css">
html {
scroll-behavior: smooth !important;
}
</style>
You could also try using vanilla JavaScript instead of jQuery:
function showIt(el_id) {
var el = document.getElementById(el_id);
el.scrollIntoView(true, {behavior: "smooth"});
}
showIt('today')
Also consider adding an itermediary element in the middle of the page, example:
<div id="middle" style="display: none;"></div>
function showIt(el_id) {
var middle_el = document.getElementById('middle');
var el = document.getElementById(el_id);
middle_el.scrollIntoView(true, {behavior: "instant"}); // Go to middle directly and then scroll slowly to #today.
el.scrollIntoView(true, {behavior: "smooth"});
}
showIt('today')
More info on scrollIntoView: https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView
Also you might be interest in: Scrolling slow on mobile/ios when using overflow:Scroll if you are on iOS
Try using easeOutCubic or another easing function (choose one here):
$(document).ready(function () {
$('html, body').animate({
scrollTop: $('#today').offset().top - 50
}, 800, "easeOutCubic");
});
The best solution for cross-browser/cross-device decent smooth scrollTop I found is using velocity.js. It's faster than jQuery's animate, quite light and supports multiple syntaxes, one of them being the one used by jQuery.animate(), so all you need to do is to replace .animate() with .velocity() (and loading the thing, of course).
I know there might be other solutions out there, but this one has been solid for years, they are always keeping it up to date, I'd say it's a keeper in any serious frontend web developer's tools. You'll find some very fancy names on velocity's libscore page. And no, I'm not affiliated. I'm just thankful for being able to use it for free.

jquery jumps instead of scrolling

For some reason my page 'jumps' instead of smoothly scrolling after clicking an internal link in menu 2nd time.
I'm quite sure that has something to do with scrolling.js file, i'm a newbie in jQuery and probably messed something up. Since you've commented that it's working just fine let me explain it on example. I enter the page I can press "About" button in menu and it scrolls just fine, I can press the "Learn About Me" button and it works fine as well, go to top arrow on the side menu works too but if you scroll manually a bit and then try to press "About" in menu it doesn't scroll but jump even if you scroll back to top and press it the same way it worked after the page load.
the page itself.
scrolling.js
$(window).scroll(function(){
var height = $('section').height();
height = height * 0.2;
if ($(window).scrollTop() >= height) {
$('nav').css('background','rgba(0,0,0,0)');
$('nav').css('margin-left','0px');
$('.OTOCWEL').css('background','rgba(0,0,0,0)');
$('#powered').css('background','rgba(0,0,0,0)').addClass('fixerpowered');
$('.menu').addClass('menuslim');
$('.menu').removeClass('menu');
$('.menuslim').css('margin-left','0px').css('opacity','1');
$('#first').addClass('mega-octicon octicon-info').css('margin-left','0px');
$('#second').addClass('mega-octicon octicon-book');
$('#third').addClass('mega-octicon octicon-mail');
$('#fourth').addClass('mega-octicon octicon-diff-added');
$('.OTOCWEL').css('display','none');
$('.suwak').css('display','none');
$('.dzolero').css('display','block');
} else {
$('nav').css('background','rgba(0,0,0,0.5)');
$('.menuslim').addClass('menu');
$('.menu').removeClass('menuslim').css('top','0px');
$('#first').html("<a>About</a>").css('margin- left','15px').removeClass('mega-octicon octicon-info');
$('#first>a').attr('href','#about');
$('#second').html("<a>Projects</a>").removeClass('mega-octicon octicon-book');
$('#second>a').attr('href','#projects');
$('#third').html("<a>Contact</a>").removeClass('mega-octicon octicon-mail');
$('#third>a').attr('href','#contact');
$('#fourth').html("<a>Additional</a>").removeClass('mega-octicon octicon-diff-added');
$('#fourth>a').attr('href','#additional');
$('.OTOCWEL').css('display','initial');
$('.suwak').css('display','block');
$('#powered').removeClass('fixerpowered');
$('.dzolero').css('display','none');
}
});
scroll.js
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
|| location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
I suspect your JQuery selector $('a[href*=#]:not([href=#])') is the source of the problem.
When it comes to your anchor links (the ones that do not redirect to a new page), you should make it such that all of them enable smooth scrolling.
Think about it, what is the main purpose of your anchor tags? It refers to a document address. The user mainly experiences:
Redirect to a new site.
Navigate through the current site.
Download request of a file.
Therefore, as long as your smooth scroll behavior is specific to all anchors; then you do not need to account for specific anchor behavior. Why? Because you do not care if the anchor redirects/download, smooth scroll should not trigger since the page does not move at all.
TLDR:
Try changing your JQuery selector from:
$('a[href*=#]:not([href=#])').click(function() { //...
To:
$('a').click(function() { //...
Do some unit testing for all scenarios. If that does not solve your problem, then we need to identify what other JavaScript is affecting your smooth scroll.
Thanks for the answer and the kudos for ideas :). I managed to change the selector so it affects all the anchor links not just the internal ones yet it didn't solve the problem. I've tried to test it with another menu section yet the result is the same. It's jumping to "Projects" section instead of smoothly scrolling. I also added instrumental button with anchor link to "Projects" section to see if it's a problem with scrolling script but it worked like a charm. Seems to me like it's a problem with menu script (scrolling.js) rather then with scroll.js
EDIT: The scrolling.js is deleting anchor links when the menu reaches 20% of section height then it rewrites them as menu goes vertical version. Is it possible that the scroll.js script is losing the focus on links as it doesn't scan the document all the time? And so is it possible to make the script rescan the document?
EDIT2: I've managed to fix it by removing the .html() function from scrolling.js

smooth scroll does not work with overflow-y

I am trying to use a smooth scroll and adopted an example I found online. Here is a fiddle with my code
https://jsfiddle.net/4DcNH/144/
I have special conditions set to html and body (basically to offset the page context by 50px from the top to avoid the navbar). Therefore the smooth scroll does not work. Does anybody know a solution to this?
thanks
carl
$(document).ready(function() {
$('a[rel="relativeanchor"]').click(function(){
$('html, body').animate({
scrollTop: $( $.attr(this, 'href') ).offset().top
}, 2000);
return false;
});
});
Is this what you're after?
$(document).ready(function () {
if(!/chrom(e|ium)/.test(navigator.userAgent.toLowerCase())){
$('html').css({'overflow-x':'auto','overflow-y':'hidden'});
}
$('a[rel="relativeanchor"]').click(function () {
var $el = $($(this).attr('href'));
$('html, body').stop().animate({
scrollTop: $el.prop('offsetTop')
}, 2000);
return false;
});
});
JSFiddle
Updates were needed in the CSS. The html overflows were removed for chrome, because otherwise, this would not work in Chrome. However, the overflows are needed for Firefox, so they are done by setting it dynamically in the JavaScript (set if not chrome).
If you want to maintain an offset, subtract it from the calculated offset. Given the above, $el.prop('offsetTop') - 50 adds 50px above.
The issue appears to be related to differences in how Chrome scrolls the <body> with height:100%. A discussion of the issue is here: Body set to overflow-y:hidden but page is still scrollable in Chrome
A workable solution is to wrap the scrolling content in <div class="content"> and disable scrolling on <body>.
Here's a JSFiddle to demonstrate the updated behavior: https://jsfiddle.net/f1zv1c5k/5/
To get the scroll to stop at the appropriate point, you need to subtract the vertical offset applied to the <html> tag (using $el.prop('offsetTop') recommended by #vol7ron) when scrolling. Your smooth scroll function would look like this:
$('a[rel="relativeanchor"]').click(function(){
var $el = $($(this).attr('href'));
$('.content').animate({
scrollTop: $el.prop('offsetTop')
}, 2000);
return false;
});

Issue on Scroll To Section

Using jQuery and Bootstrap 3 I am trying to create a one page Scrolling Website. Here is the Working Demo . So far it looks fine when user scrolls in sequence like from Section 1 to Section 2 or Section 2to Section 3 but I have some issue on nav navbar-nav items when user scrolls out of order like from Section 1 to Section 6. It looks like nav navbar-nav steps on each items to get the target item!(As you can see in following image)
There is also one other important issue on Section 7 scrolling. which it not scrolls to the same positions as other sections and there is more space. (As you can see in following image)
Here is the jquery which I used for Scrolling
<script>
$(function() {
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
});
</script>
Can you please help me to fix these thing on the code? Thanks
1) The problem with the last section should be ease to fix. There is not enought "room" underneath the last section and so the browser cannot scroll any further. A quick and dirty fix for that would be to insert some
<p> </p>
lines at the end of the last paragraph.
2) I think this could be tricky. The problem is that not the Sections, but the "html" and "body" elements are scrolled. That means if the user is at the first section and clicks on the last section the whole page is scrolled. The user sees all content during the scroll animation. I think that is how it is supposed to work. Otherwise you would have to change how and what you actually scroll.

Categories

Resources