Show next div on scroll Down/Up - javascript

First I use an library to animate going from #one to #two with this code:
$(function() {
$('a.page-scroll').bind('click', function(event) {
var $anchor = $(this);
$('html, body').stop().animate({
scrollTop: $($anchor.attr('href')).offset().top
}, 1500, 'easeInOutExpo');
event.preventDefault();
});
});
my html is:
<div id="indicators">
<a href="#one" class="btn page-scroll" style="border-radius: 50%;"><i class="fa fa-circle" aria-hidden="true"></i>
</a>
<a href="#two" class="btn page-scroll"><i class="fa fa-circle" aria-hidden="true"></i>
</a>
<a href="#three" class="btn page-scroll"><i class="fa fa-circle" aria-hidden="true"></i>
</a>
</div>
so now when I click on some indicator (circle icon) send me with animation to there div but what I want to do now is when user have focus on some div and when scroll down to show to them new #id with animation...
etc. user have focus in #two and when scroll down a little to show them #three with animation ...
var lastScrollTop = 0;
$(window).scroll(function(event){
var st = $(this).scrollTop();
if (st > lastScrollTop){
//down
} else {
// up
}
lastScrollTop = st;
});
How to find on which div user make scroll? Also what I need to do is like on this website: http://hotelgene.com/

I think it is not the question about how to find user is looking at which page.
Just make sure no matter how many times user scrolling, the scroll-height always keep in the right position. You just listen to the mouse event, if user scroll down too much, they will scroll up again.

Try this
$(document).scroll(function() {
var y = $(this).scrollTop();
//200 is the total height of divs before div with animation enters viewport
if (y > 200) {
$('.three').addClass("animation");
} else {
$('.three').removeClass("animation");
}
.one {
height: 100px;
}
.two {
height: 100px;
}
.three {
height: 100px;
}
.animation {
transition: all ease-in 0.2s /* or any transition you choose*/
}
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
This should help you out.

Related

JavaScript smooth scroll not working in safari browser

I have created small menu order application, I have added 5 menu categories is Desserts, salad, thai noodles and more using horizontal scroll bar. if I click salad or any categories move left and right position working fine in chrome. I checking safari browser not working horizontal scroll. what I am missing. could you please check and let me know.
html:
<div class="menu" id="menu">
<div class="topnav sticky" id="stickyMenu"><span data-id="appetizers" id="nav1" class="cat-nav">Appetizers</span><span data-id="desserts" id="nav2" class="cat-nav">Desserts</span><span data-id="pizza--classic-11-inches-" id="nav3" class="cat-nav active">Pizza (Classic 11 inches)</span><span data-id="salad" id="nav4" class="cat-nav">Salad</span><span data-id="thai-noodles" id="nav5" class="cat-nav">Thai Noodles</span></div>
<!-- <div class="row filter">
<input type="text" id="gsearch" class="form-control gsearch" placeholder="Search within this Menu...">
</div> -->
</div>
js code:
$(document).on('click', ".topnav .cat-nav", function(e) {
$(".topnav .cat-nav").removeClass("active");
$(this).addClass("active");
var target = $(this).data("id");
$('html, body').animate({
scrollTop: ($("#"+target).offset().top - 50)
}, 500);
});
$(window).scroll(function() {
//get current sroll position
var scrollPosition = $(window).scrollTop();
//get the position of the containers
var s=["appetizers","desserts","pizza--classic-11-inches-","salad","thai-noodles"];
for (i=0; i<s.length; i++) {
if (scrollPosition >= ($("#"+s[i]).offset().top) - 190) {
$("#nav"+(i+1)).addClass("active");
$("#nav"+(i+1)).siblings().removeClass("active");
// $('.cat-nav').scrollLeft(myScrollPos);
var element = document.querySelector(".active");
element.scrollIntoView({behavior: "smooth" ,inline: "center"});
// $("#nav"+(i+1)).css({behavior: "smooth" ,inline: "center"});
}
}
});
Add overflow: auto to your sticky or topnav class:
.sticky {
overflow: none;
overflow-x: auto;
display: block;
}
This might work.

class swap on scroll in JQuery

I'm working on a navbar whichs swaps classes to fade the background in and out.
I've targeted the window itself and listen to the scroll, determining on how far down the user is at the page, if the user if further down than 800px, the navbar should fade out, if the user scrolls back up to the top, the navbar should fade in again
This is what I have:
Javascript:
$(window).scroll(function() {
if ($(this).scrollTop() > 800) {
$( "#nav" ).removeClass('.menuOut', 500);
$( "#nav" ).addClass('.menuIn', 500);
} else {
console.log('there');
$( "#nav" ).removeClass('.menuIn', 500);
$( "#nav" ).addClass('.menuOut', 500);
}
});
</script>
Navbar:
<nav id="nav" class="navbar menuIn">
<!--Content-->
</nav>
CSS:
.menuIn {
background-color: rgba(50,50,50,50.3);
}
.menuIn {
background-color: rgba(50,50,50,1);
}
(example of what I mean: http://www.albdifferent.com/)
Try with this below code it may help you.
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 800) {
$("#nav").removeClass("menuOut");
$("#nav").addClass("menuIn");
} else {
$("#nav").removeClass("menuIn");
$("#nav").addClass("menuOut");
}
});

Having trouble getting the scroll animation to not trigger the scroll event

I currently have a number of div tags that can be seen below that are each the height of the viewport.
<!-- .current represents the div the user is currently viewing -->
<div class="full-height current" id="id1">
<div class="container">
</div>
</div>
<div class="full-height" id="id2">
<div class="container">
</div>
</div>
<div class="full-height" id="id3">
<div class="container">
</div>
</div>
<div class="full-height" id="id4">
<div class="container">
</div>
</div>
<div class="full-height" id="id5">
<div class="container">
</div>
</div>
I am attempting to implement a feature where upon a user scrolling, the window will scroll to the next div tag, always having only one div in view at a time. The way I implemented it works great, except for the fact that the animation triggers the scroll event again, resulting in an endless loop of the page scrolling once the user scrolls at all. I attempted to fix this by having a variable that will stop the event from triggering if the animation is in progress, but it does not seem to work. I am aware that I didn't do it for the scroll up, but I just wanted to see if it worked for the down first.
$(window).scroll(function(event) {
var scrollTop = $(this).scrollTop();
// If user scrolls down
if ((scrollTop > lastScrollTop) && $(".current").next("div").length > 0) {
if (animating == false) {
console.log("down");
$(".current").next("div").addClass("current");
$(".current").first().removeClass("current");
animating = true;
$("html, body").animate({
scrollTop: $(".current").offset().top
}, 1000, function() {animating = false});
}
// If user scrolls up
} else {
if ($(".current").prev("div").length > 0) {
console.log("up");
$(".current").prev("div").addClass("current");
$(".current").last().removeClass("current");
$("html, body").animate({
scrollTop: $(".current").offset().top
}, 1000);
}
}
lastScrollTop = scrollTop;
});
CSS included just in case. The 100vh - 111px is due to a fixed navbar at the top that is 111px high
/* Makes the element take up the entire height of the screen */
.full-height{
height: -o-calc(100vh - 111px); /* opera */
height: -webkit-calc(100vh - 111px); /* google, safari */
height: -moz-calc(100vh - 111px); /* firefox */
}
#id1 {
background-color: red;
}
#id2 {
background-color: blue;
}
#id3 {
background-color: yellow;
}
#id4 {
background-color: green;
}
#id5 {
background-color: purple;
}
If anyone could give me any ideas for fixing my problem, that would be great.
You'll want to stop the event and preventDefault. Here is some code from a current landing page:
$(document).ready(function () {
$('a.page-scroll').on('click', function(event) {
var link = $(this);
$('html, body').stop().animate({
scrollTop: $(link.attr('href')).offset().top - 50
}, 500);
event.preventDefault();
});
$('body').scrollspy({
target: '.navbar-fixed-top',
offset: 80
});
});
It uses bootstrap scrollspy so just ignore that. But notice that it stops any scroll animation that could be running and then also calls event.preventDefault() to stop the scroll event from bubbling and thus becoming recursive.
EDIT:
O.k. so I've a better look and the basic problem re: infinite scrolling is the code doesn't check if the scrollTop is already at 'where it needs to be'. You need an additional check to short circuit the scroll:
if (animating == false) {
if ($(this).scrollTop() == lastScrollTop) return;
if (($(this).scrollTop() > lastScrollTop) && $(".current").next("div")) {
console.log("down");
$(".current").next("div").addClass("current");
$(".current").first().removeClass("current");
animating = true;
$("html, body").stop().animate({
scrollTop: $(".current").offset().top
}, 1000,
function () { lastScrollTop = $(this).scrollTop(); animating = false; });
// If user scrolls up
} else {
if ($(".current").prev("div").length > 0) {
console.log("up");
$(".current").prev("div").addClass("current");
$(".current").last().removeClass("current");
$("html, body").stop().animate({
scrollTop: $(".current").offset().top
}, 1000, function () { lastScrollTop = $(this).scrollTop(); animating = false; });
}
}
}
Otherwise as it stands it will always either scroll up or down and never settle. That said with that "working" it's a terrible user experience. It will jump about since your scroll to code will fight the user on current scrollTop if they keep scrolling. i.e. your code will make it jump back to a previous position.
Try defining scroll event handler as named function ; defining lastScrollTop outside of scroll handler ; substituting .one() for .on() to allow animation to complete before re-attaching scroll event ; use .promise() which should be called at most once to avoid .animate() complete callback being called twice with selector "html, body" ; substituting single if to check for next or previous element .length and .animate() call for multiple if..else conditions and statements, animation function calls ; re-attach scroll event at .then() following animation completion .promise()
var lastScrollTop = 0;
function scroller(event) {
var scrollTop = $(this).scrollTop();
var direction = scrollTop > lastScrollTop ? "next" : "prev";
var el = $(".current")[direction](".full-height");
console.log(direction === "next" ? "down" : "up");
if (el.is("*")) {
$("html, body").animate({
scrollTop: el.offset().top
}, 1000).promise().then(function() {
console.log(this)
lastScrollTop = $(window).scrollTop();
$(".current")
.removeClass("current")[direction]("div")
.addClass("current")
setTimeout(function() {
$(window).one("scroll", scroller)
})
});
} else {
lastScrollTop = scrollTop;
$(window).one("scroll", scroller)
}
}
$(window).one("scroll", scroller);
/* Makes the element take up the entire height of the screen */
.full-height {
height: -o-calc(100vh - 111px);
/* opera */
height: -webkit-calc(100vh - 111px);
/* google, safari */
height: -moz-calc(100vh - 111px);
/* firefox */
}
#id1 {
background-color: red;
}
#id2 {
background-color: blue;
}
#id3 {
background-color: yellow;
}
#id4 {
background-color: green;
}
#id5 {
background-color: purple;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- .current represents the div the user is currently viewing -->
<div class="full-height current" id="id1">
<div class="container">
</div>
</div>
<div class="full-height" id="id2">
<div class="container">
</div>
</div>
<div class="full-height" id="id3">
<div class="container">
</div>
</div>
<div class="full-height" id="id4">
<div class="container">
</div>
</div>
<div class="full-height" id="id5">
<div class="container">
</div>
</div>
If you define height 100vh ,scroll event wont trigger

Scroll to top button showing when not on top of the page

I would like to have a scroll to top arrow fixed in my page using angular bootstrap.
Currently I have
<div class="col-md-1">
<div class="affix">
<div>
<a th:href="#{/}" href="#" target="_self"><img id="image" src="source" alt="yoli" width="50px" /></a>
</div>
Scroll to top
</div>
</div>
<div class="col-md-6">
<div id="search-bar" ng-include="blabla"></div>
<li ng-repeat="something"></li>
</div>
However when the "Scroll to top" is click it only works first time since the url changes to ...#search-bar and when you click it again nothing happens. So how do I scroll to top without changing the url?
And also question how do I make the "Scroll to top" only show when the search-bar is not showing?
I was thinking about using $anchorScroll and using id'ed numbers on li and if it's higher then "element-3" then show the button, however not sure if that would work.
UPDATE:
I am thinking of following this example, that is using navigation bars that is #search and #results and make the #search href visible on #results active and #results one hidden.
You can do this without jQuery as well:
function filterPath(string) {
return string
.replace(/^\//, '')
.replace(/(index|default).[a-zA-Z]{3,4}$/, '')
.replace(/\/$/, '');
}
const locationPath = filterPath(location.pathname);
document.querySelectorAll('a[href*="#"]').forEach(link => {
let thisPath = filterPath(link.pathname) || locationPath;
if ((location.hostname == link.hostname || !link.hostname)
&& (locationPath == thisPath)
) {
let hashName = link.hash.replace(/#/, '');
if (hashName) {
let targetEl = document.getElementById(hashName);
if (targetEl) {
link.addEventListener('click', () => {
event.preventDefault();
targetEl.scrollIntoView({
top: 50,
left: 0,
behavior: "smooth"
});
});
}
}
}
});
Here is how you can do it. Create a button:
Scroll To Top
CSS:
.scrollToTop{
width:100px;
height:130px;
padding:10px;
text-align:center;
background: whiteSmoke;
font-weight: bold;
color: #444;
text-decoration: none;
position:fixed;
top:75px;
right:40px;
display:none;
background: url('arrow_up.png') no-repeat 0px 20px;
}
.scrollToTop:hover{
text-decoration:none;
}
JavaScript:
$(document).ready(function(){
//Check to see if the window is top if not then display button
$(window).scroll(function(){
if ($(this).scrollTop() > 100) {
$('.scrollToTop').fadeIn();
} else {
$('.scrollToTop').fadeOut();
}
});
//Click event to scroll to top
$('.scrollToTop').click(function(){
$('html, body').animate({scrollTop : 0},800);
return false;
});
});
You can find a demo here. The source presented is taken from here.

How to scroll back to the top of page on button click?

I am creating my product pages by using the object tag code, but every time I click the "view" button, the next page is staying at the same position of previous page which I just viewed. How can I add functionality that will let me view from the top of page every time I click the "view" button?
<div id="container" class="clearfix"><!--! end of #sidebar -->
<div class="holder"></div>
<div id="content" class="defaults"><!-- navigation holder -->
<div id="title2">Office Section</div>
<!-- item container -->
<ul id="itemContainer">
<li>
<div id="product">
<div id="title">FuBangĀ®</div>
<div class="imageOuter" style="margin:0">
<a class="image" href="officesection010.html">
<span class="rollover" ></span>
<img class="imgborder" src="product/officesection/010.jpg" width="165" height="165" />
</a>
</div><br />
<div id="text">Sofa </div><br />
<div id="button">
View Details
</div>
</div>
</li>
</ul>
<br />
<div id="title2"></div>
<div class="holder"></div>
</div>
</div> <!--! end of #content -->
</div> <!--! end of #container -->
When I click the "View Details" button at a specific position "x" here: http://postimg.org/image/vgs0lwhtr/
The next page shows the same position "x", but I want it to jump to the top of page:
http://postimg.org/image/vn80e2lph/
Using Javascript:
document.body.scrollTop = document.documentElement.scrollTop = 0;
Using jQuery:
$(function() {
$('body').scrollTop(0);
});
jQuery(document).ready(function($){
$(window).scroll(function(){
if ($(this).scrollTop() > 50) {
$('#backToTop').fadeIn('slow');
} else {
$('#backToTop').fadeOut('slow');
}
});
$('#backToTop').click(function(){
$("html, body").animate({ scrollTop: 0 }, 500);
//$("html, body").scrollTop(0); //For without animation
return false;
});
});
please refere this, may this help
Sometimes placing scroll to body doesn't work if your current content is generated through jQuery (as it was in my case). In such situation you can just do following.
$(function() {
$('html').scrollTop(0);
});
A small issue with Subhash's jQuery solution is that you must call this code within $(document).ready() in order for your $('body') selector to work. The ready event may not fire before parts of your page have been rendered to the screen.
An better approach is to simply modify the user's location as a work-around to this browser 'feature':
//Above all of your $(document).ready(...) code
document.location = "#";
Simple HTML solution for jumping between page parts
// Place a tag like this where you would like to go
// in your case at the top
<a name="top"></a>
// you will reach there by click of this link better use an image reach their by clicking on this we can also use an image, align in right
last
Back to top button, works in all browsers.To change the scroll speed simply change the x in counter -= x here x = 10
function scrollToTop(){
var myBody = document.body;
var id = setInterval(secondFunction,1);
var height = window.pageYOffset;
var counter = height;
function secondFunction(){
if(window.pageYOffset == 0){
clearInterval(id);
}
else {
if(!!navigator.userAgent.match(/Trident/g) || !!navigator.userAgent.match(/MSIE/g)){
counter -= 10;
counter--;
document.documentElement.scrollTop = counter;
}
else {
counter -= 10;
counter--;
myBody.scrollTop = counter;
}
}
}
}
body {
height: 5000px;
margin: 0;
padding: 0;
}
.backToTop {
position: fixed;
/* Fixed at page */
top: auto;
bottom: 20px;
left: auto;
right: 20px;
background-color: crimson;
color: white;
padding: 5px;
cursor: pointer;
}
header {
position: relative;
top: 0;
left: 0;
width: 100%;
height: 100px;
background-color: black;
}
<!-- back to top button -->
<span class="backToTop" onclick="scrollToTop()">TOP</span>
<!-- Header -->
<header>
</header>
Assign an id="#body" and tabindex in the <body> tag
<body id="#body" tabindex="1">
and use jquery focus()
$(function() {
$("#body").attr("tabindex",-1).focus();
}
You can use this method:
function gototop() {
if (window.scrollY>0) {
window.scrollTo(0,window.scrollY-20)
setTimeout("gototop()",10)
}
}

Categories

Resources