How to make this scroll to div script "smooth" - javascript

So I found this script by a user of this site however I can't remember the author. The script is working, however I want it to scroll more "smoothly" than just instantly appear at my desired information. And if possible, have the destination appear 300pixels above the div.
How do I do that?
#general{
margin-top:900px;
height: 100px;
weight: 100px;
background: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
var hashTagActive = "";
$(".scroll").click(function (event) {
if(hashTagActive != this.hash) { //this will prevent if the user click several times the same link to freeze the scroll.
event.preventDefault();
//calculate destination place
var dest = 0;
if ($(this.hash).offset().center > $(document).height() - $(window).height()) {
dest = $(document).height() - $(window).height();
} else {
dest = $(this.hash).offset().center;
}
//go to destination
$('html,body').animate({
scrollTop: dest
}, 2000, 'swing');
hashTagActive = this.hash;
}
});
</script>
<div>
<a class="scroll" href="#general">Hello</a>
</div>
<div id="general">
</div

For a smoother scroll you can use:
$(document).ready(function() {
$("ANCHOR LINK").click(function(event){
event.preventDefault();
$("html, body").animate({scrollTop:$(this.hash).offset().top}, 1000);
});
});
And you see the last number? 1000, make it bigger to make it slower.
The second thing I'm afraid I can't help you with.

How to animate to #id links:
jsfiddle
HTML
Click me!<br>
Google.com
<div id="content"></div>
CSS
#content {
margin-top: 900px;
height: 100px; width: 100px;
background-color: lightgreen;
}
jQuery
$('a').on('click', function (event) {
var target = $(this.hash),
top;
if (target) {
top = target.offset().top;
event.preventDefault();
$('html, body').animate({
scrollTop: top
}, 600, 'swing');
}
});

For smooth scroll to 300px above top of the element, your JavaScript function should look like this :
$(".scroll").click(function (event) {
$('html,body').animate({
scrollTop: ($(this.hash).offset().top - 300)
}, 2000);
event.preventDefault();
});

Related

Animated scroll with JQuery

How is it possible to make the text I am not clickable for some reason... (check the code below) clickable?
var container = document.querySelector('.container');
var clickMe = document.querySelector('.clickMe');
clickMe.addEventListener('click', function() {
var container = document.querySelector('.container');
$([document.documentElement, document.body]).animate({
scrollTop: $(".container").offset().top
}, 1000);
});
container.addEventListener('wheel', function() {
var scrollY = window.scrollY;
if (scrollY == 0) {
$([document.documentElement, document.body]).animate({
scrollTop: $(".nextContainer").offset().top
}, 800);
}
});
.container {
background: green;
height: 100vh;
width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<p class="clickMe">'wheel'</p>
</div>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<div class="nextContainer">
<p class="clickMe">I am not clickable for some reason...</p>
</div>
As you see, the Wheel-listener works perfectly, while the click-listener does not. How do I solve this problem, if possible?
Thanks in advance.
The problem appear because you get only first clickable element here :
var clickMe = document.querySelector('.clickMe');
So, you attach the click event just at first element "wheel" text.
The solution to fix this problem is to get all ".clickMe" elements with querySelectorAll and attach click event to each element.
var clickMe = document.querySelectorAll('.clickMe');
clickMe[0].addEventListener('click', function() {
var container = document.querySelector('.container');
$([document.documentElement, document.body]).animate({
scrollTop: $(container).offset().top
}, 1000);
});
clickMe[1].addEventListener('click', function() {
var container = document.querySelector('.container');
$([document.documentElement, document.body]).animate({
scrollTop: $(container).offset().top
}, 1000);
});
Are you sure it's not clickable. In function which handle paragraph click add console.log("CLICKED"); and see in console if anything appears when you click. And in css add style for clickMe cursor:pointer; so when you hover it looks better.
Finally figured out the problem.
After the animation,
$([document.documentElement, document.body]).animate({
scrollTop: $(".nextContainer").offset().top
}, 800);
I needed to add JQuery:s stop() function,
$('html, body').stop();
Credits: Stop ScrollTop function when user scrolls jquery
Instead of document.querySelector('.clickMe') you can use the jQuery Selector $('.clickMe').
Than it works fine.
var container = document.querySelector('.container');
var clickMe = document.querySelector('.clickMe');
console.log(clickMe);
$('.clickMe').on('click', function() {
console.log('clicked');
var container = document.querySelector('.container');
$([document.documentElement, document.body]).animate({
scrollTop: $(".container").offset().top
}, 1000);
});
container.addEventListener('wheel', function() {
var scrollY = window.scrollY;
if (scrollY == 0) {
$([document.documentElement, document.body]).animate({
scrollTop: $(".nextContainer").offset().top
}, 800);
}
});
.container {
background: green;
height: 100vh;
width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<p class="clickMe">'wheel'</p>
</div>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<div class="nextContainer">
<p class="clickMe">I am not clickable for some reason...</p>
</div>

Modify existing jQuery to change URL on Scroll

I have a jQuery code obtained from w3schools.com which ON CLICK (clicking an ) changes URL's #id and also allows smooth scrolling to a particular DIV section. But its not working on scroll. I want the same with an scrolling effect. When I scroll down or up to a particular section the URL's #id should change.
Current jQuery Code:
$(document).ready(function(){
$("#navlist a").on('click', function(event) {
if(this.hash !== ""){
var hash = this.hash;
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function(){
window.location.hash = hash;
});
}
});
});
I searched on stackoverflow and I got something like this:
$(document).bind('scroll',function(e){
$('div').each(function(){
if ($(this).offset().top < window.pageYOffset + 10 && $(this).offset().top + $(this).height() > window.pageYOffset + 10){
window.location.hash = $(this).attr('id');
}
});
});
This seems to work but when I place both the code either one of them is stopping the other one from executing. I thought of combining both the codes into one to achieve both onclick and scroll effect but I am not being able to do so (weak hands on jquery yet).
Example URL with ID: http://localhost/sites/fh/index.php#first
Please help me devs.
Instead of setting the location hash, you should change the history state. That way you will avoid forced page scrolling by browser. Check it below:
navlist = [];
$("#navlist a").each(function(i) {
var thisLink = $(this);
var thisId = thisLink.attr('href');
var thisTarget = $(thisId);
navlist.push({
'anchor': thisLink,
'id': thisId,
'target': thisTarget
});
thisLink.on('click', function(e) {
e.preventDefault();
$('html, body').animate({
scrollTop: thisTarget.offset().top
}, 800);
});
});
$(window).on('scroll resize', function(e) {
$.each(navlist, function(e, elem) {
var placement = elem.target[0].getBoundingClientRect();
if( placement.top<window.innerHeight && placement.bottom>0 ) {
history.pushState({}, '', elem.id);
console.log('Hash: ' + elem.id);
return false; /* Exit $.each loop */
};
});
});
nav a {
display: block;
}
section {
height: 600px;
border-top: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav id="navlist">
Go to Section 1
Go to Section 2
Go to Section 3
</nav>
<section id="s1">Section 1 Content</section>
<section id="s2">Section 2 Content</section>
<section id="s3">Section 3 Content</section>
Also on JSFiddle.
Please note, if you are using Foundation framework, than you already have Magellan.
For Bootstrap it is called ScrollSpy.

How to move the page up each time to a div

I am creating a form where i have many child forms to submit,so i have used a jQuery functionality where each submit a msg will show at the top of the page ,now what i want,on each submit the page will scroll up to the div where that jQuery is calling .Here is my code
var url = "<%=addPersonalDetailsURL%>";
var type = "addPersonalDetails";
if(!($('#<portlet:namespace/>address1').val()=='' || $('#country').val()=='None' ||$('#<portlet:namespace/>primaryPhone').val()=='')){
jQuery.getJSON(url+"&address1="+address1+"&address2="+address2+"&country="+country+"&state="+state+"&city="+city+"&zip="+zip+"&skypeId="+skypeId+"&twitter="+twitter+"&primaryPhone="+primaryPhone+"&secondaryPhone="+secondaryPhone+"&type="+type, function(data) {
$('html, body').animate({
scrollTop: $(".success").offset().top
}, 800);
for(var z=0; z<data.applicationArray.length;z++){
applicationArray = data.applicationArray[z].split("$$##$$##");
address1 = applicationArray[0];
address2 = applicationArray[1];
city = applicationArray[2];
primaryPhone = applicationArray[3];
}
jQuery.getJSON is giving some result where on the basis i have to use that functionality.So can you tell how i should modify your solution
You should need to get your element's top position in the page and move the scroll to that position. Something like the code below:
jQuery(window).scrollTop(jQuery(".success").offset().top);
Note that the code above will move to the first .success position. If you have to reference a specific one, add the index in the selector, for example:
jQuery(window).scrollTop(jQuery(".success:eq(1)").offset().top);
You can do that with this function:
$("button").click(function () {
$('html, body').animate({
scrollTop: $(".whichElement").offset().top
}, 800);
});
Explanation:
If the button is clicked, we scroll the page to the element with class
whichElement and the duration of the scroll is 800ms.
Example:
$(".first-hey").click(function () {
$('html, body').animate({
scrollTop: $(".second-hey").offset().top
}, 800);
});
$(".second-hey").click(function () {
$('html, body').animate({
scrollTop: $(".third-hey").offset().top
}, 800);
});
$(".third-hey").click(function () {
$('html, body').animate({
scrollTop: $(".first-hey").offset().top
}, 800);
});
.divide {
height: 1300px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="first-hey">First hey</button>
<div class="divide"></div>
<button class="second-hey">Second hey</button>
<div class="divide"></div>
<button class="third-hey">Third hey</button>

Issue with jQuery scrolling

So I'm building a website for a friend and I want it to scroll on href clicks, that is easy, I managed to do it with smooth animation. But the problem is, when I load the page and click on the FIRST link, scrolling is not precise, and after I click on anything after Test1 is pressed, its not precise again.
Since it's hard for me to explain, ill post jsfiddle link so you can test it.
$(document).ready(function() {
$('.click').click(function(e){
// prevent default action
e.preventDefault();
scrollToElement( $(this).attr('href'), 1000 );
});
var scrollToElement = function(el, ms){
var speed = (ms) ? ms : 600;
$('html,body').animate({
scrollTop: $(el).offset().top-102
}, speed);
}
});
Full code here: http://jsfiddle.net/pxmfs78k/
How to test my problem:
Press any link first time, and then you will see that the div is not positioned where I wanted it to be, and if you press the same link again, it will position itself correctly, and after that there are no problems in clicking until you reload or press test1 link, the first one.
So any idea what might cause the problem?
And I read this https://stackoverflow.com/questions/19750702/jquery-scrolling-issues-with-scrolltop thread and I couldn't fix my problem with the explanation given there.
It's because you're setting the nav to sticky, thus, removing it from the flow, and the whole content jumps up by 102px, to fix this, give the sticky class to the body instead of the nav and use padding to fight against it. http://jsfiddle.net/pxmfs78k/1/
CSS
body.sticky {
padding-top: 102px;
}
body.sticky .nav {
position: fixed;
width: 100%;
left: 0;
top: 0;
z-index: 100;
border-top: 0;
}
JS
$(document).ready(function () {
var stickyNavTop = $('.nav').offset().top;
var stickyNav = function () {
var scrollTop = $(window).scrollTop();
if (scrollTop > stickyNavTop) {
$('body').addClass('sticky');
} else {
$('body').removeClass('sticky');
}
};
stickyNav();
$(window).scroll(function () {
stickyNav();
});
});
$(document).ready(function () {
$('.click').click(function (e) {
// prevent default action
e.preventDefault();
scrollToElement($(this).attr('href'), 1000);
});
var scrollToElement = function (el, ms) {
var speed = (ms) ? ms : 600;
$('html,body').animate({
scrollTop: $(el).offset().top - 102
}, speed);
}
});

Automatically Scroll Page from Top to Bottom, then Back Up (and Repeat)

I'm trying to figure out how to, upon pageload, automatically scroll to the bottom of a page (which has been described sufficiently here) and then scroll back up automatically upon reaching the bottom of the page. I can find the automatic scrolling to the bottom, but I can't figure out how to identify when I'm at the bottom of the page, and how to scroll back up when I am. I'd do this using generic Javascript (or JQuery).
Thanks in advance!
Try this:
http://jsfiddle.net/yjYJ4/
$('html, body').animate({ scrollTop: $(document).height() - $(window).height() }, 1000, function() {
$(this).animate({ scrollTop: 0 }, 1000);
});
You can view the demo in full screen here: http://jsfiddle.net/yjYJ4/embedded/result/
Change the number "1000" if you want to increase or decrease speed.
Works fine in Chrome, Firefox and IE 6-9.
EDIT:
If you need it to repeat forever (not recommended...) you could do like this: http://jsfiddle.net/QUCWe/
here is the example using Pure JavaScript
<script type="application/javascript">
var Height = document.documentElement.scrollHeight;
var currentHeight = 0;
var bool = true;
var step = 5;
var speed = 10;
var interval = setInterval(scrollpage, speed)
function scrollpage() {
if (currentHeight < 0 || currentHeight > Height)
bool = !bool;
if (bool) {
window.scrollTo(0, currentHeight += step);
} else {
// if you don't want to continue scroll
// clearInterval(interval) use clearInterval
window.scrollTo(0, currentHeight -= step);
}
}
</script>
<style type="text/css">
#top {
border: 1px solid black;
height: 10000px;
}
#bottom {
border: 1px solid red;
}
</style>
<div id="top">top</div>
<div id="bottom">bottom</div>
You can pass a function as an argument, which will be called when the end has reached. I've just written a jQuery plugin for this purpose. Fiddle: http://jsfiddle.net/kKaWZ/
(function($){
$.fn.downAndUp = function(time, repeat){
var elem = this;
(function dap(){
elem.animate({scrollTop:elem.outerHeight()}, time, function(){
elem.animate({scrollTop:0}, time, function(){
if(--repeat) dap();
});
});
})();
}
})(jQuery);
$("html").downAndUp(2000, 5)
Be aware that the suggested infinite scroll JSFiddle code will work in firefox however will not work in Chrome/Chromium without a valid
<!DOCTYPE html>
tag at the start of ones page. Per This Answer
$("body").animate({ scrollTop: '1000' }, 500, function(){
$("body").animate({ scrollTop: '0' }, 500, function(){
$("body").animate({ scrollTop: '1000' }, 500);
});
});

Categories