I have a page with a lot of text that requires some amount of scrolling. I was able to get a button, when clicked, to shoot to the top of the page I am on. But when at the top of the page, I am wanting this button to switch to another link that goes to the homepage.
Bonus Points: How would I change the text to also switch from "top" to "home"? I have not tackled this hurdle because I figured my issue with switching the href would correlate to this obstacle.
JS:
window.onscroll = function() { scrollFunction() };
function scrollFunction() {
document.getElementById("scroll-to-top-button").classList.toggle("show");
window.onclick = function(event) {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
window.location = "#top";
} else if(document.body.scrollTop = 0){
window.location.href = "https://homepage.html";
}
}
}
html:
<div class="fas fa-angle-up">top</div>
I have tried using window.scrollY instead of .scrollTop - but I have not touched scrolling elements prior to this. I am a little fuzzy with how to indicate if I have scrolled vs not scrolled. I do not know if my issue is because my if, else elements are not correct - or if it is something else?
Here's a small code snippet example to answer your question,
const anchor = document.querySelector('a')
window.addEventListener('scroll',() => {
if(window.scrollY > 100){
anchor.setAttribute('href', "#above")
anchor.innerText = "go above"
}else{
anchor.setAttribute('href', "#below")
anchor.innerText = "go below"
}
})
html{
scroll-behavior: smooth;
}
header{
background: white;
width: 100%
}
#above{
height:100vh;
width: 100%;
background: blue;
}
#below{
height: 100vh;
width: 100%;
background: green;
}
<header style="position:fixed">
go below
</header>
<section id="above"></section>
<section id="below"></section>
Here I am using setAttribute() to change the href attribute of anchor tag, and innerText to change that same anchor tag's text. I am using scrollY to check amount of window scrolled.
You could change the if(window.scrollY > 'change this value') according to your need
Related
Smooth scrolling effect in JQuery not working in IE & Mozila Browsers, its fine in Chrome browser can any one help on this. iam using this code. some times working in mozila but in IE. please ignore stickit() function.
Thanks in Advance.
< script src = "https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js" > < /script> <
script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js" > < /script> <
script src = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" > < /script> <
script src = "scroll_110.js" > < /script>
$(document).ready(function() {
// Add scrollspy to <body>
$('a').scrollspy({
target: "a",
offset: 50
});
// Add smooth scrolling on all links inside the navbar
$("a").on('click', function(event) {
// Make sure this.hash has a value before overriding default behavior
if (this.hash !== "") {
// Prevent default anchor click behavior
event.preventDefault();
// Store hash
var hash = this.hash;
// Using jQuery's animate() method to add smooth page scroll
// The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
$('body').animate({
scrollTop: $(hash).offset().top
}, 1200, function() {
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
} // End if
});
});
// Create a clone of the menu, right next to original.
jquery('.menu').addClass('original').clone().insertAfter('.menu').addClass('cloned').css('position', 'fixed').css('top', '0').css('margin-top', '0').css('z-index', '500').removeClass('original').hide();
scrollIntervalID = setInterval(stickIt, 10);
function stickIt() {
var orgElementPos = jquery('.original').offset();
orgElementTop = orgElementPos.top;
if (jquery(window).scrollTop() >= (orgElementTop)) {
// scrolled past the original position; now only show the cloned, sticky element.
// Cloned element should always have same left position and width as original element.
orgElement = jquery('.original');
coordsOrgElement = orgElement.offset();
leftOrgElement = coordsOrgElement.left;
widthOrgElement = orgElement.css('width');
jquery('.cloned').css('left', leftOrgElement + 'px').css('top', 0).css('width', widthOrgElement).show();
jquery('.original').css('visibility', 'hidden');
} else {
// not scrolled past the menu; only show the original menu.
jquery('.cloned').hide();
jquery('.original').css('visibility', 'visible');
}
}
#top,
#middle,
#bottom {
height: 1600px;
width: 900px;
background: green;
}
.menu {
background: #fffff;
color: #333;
height: 40px;
line-height: 40px;
letter-spacing: 1px;
width: 100%;
}
<div class="menu">
Top
Middle
Bottom
</div>
<div id="top">
Top</div>
<div id="middle">
Middle</div>
<div id="bottom">
Bottom</div>
the solution would be to use both html and body in JQ -> $('html,body').animate
see below ( i removed the scrollspy code as it's not relevant to this question, but you should keep it )
$(document).ready(function() {
// Add scrollspy to <body>
// Add smooth scrolling on all links inside the navbar
$("a").on('click', function(event) {
// Make sure this.hash has a value before overriding default behavior
if (this.hash !== "") {
// Prevent default anchor click behavior
event.preventDefault();
// Store hash
var hash = this.hash;
// Using jQuery's animate() method to add smooth page scroll
// The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
$('html,body').animate({
scrollTop: $(hash).offset().top
}, 1200, function() {
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
} // End if
});
});
div {
height: 500px;
width: 100%;
background: red;
border-top: 10px solid blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>Section1</li>
<li>Section2</li>
<li>Section3</li>
</ul>
<div id ="section1">
</div>
<div id ="section2">
</div>
<div id ="section3">
</div>
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.
I have a very long article page that I want to help mobile users scroll on. For very long lists in mobile apps there's usually a alphabetical index that can help users jump to various places in the list. How do I implement something like that for a webapp?
If it helps my stack is angularjs / jquery / phonegap.
Just use angular's built-in $anchorScroll service.
See the live example in angular's official docs. Here are the important pieces of code:
In your view template:
<div id="scrollArea" ng-controller="ScrollCtrl">
<a ng-click="gotoBottom()">Go to bottom</a>
<a id="bottom"></a> You're at the bottom!
</div>
In your controller:
function ScrollCtrl($scope, $location, $anchorScroll) {
$scope.gotoBottom = function (){
// set the location.hash to the id of
// the element you wish to scroll to.
$location.hash('bottom');
// call $anchorScroll()
$anchorScroll();
};
}
iOS7 Style List Navigator
If you want something nice on the phone, I just wrote this iOS7 style list navigator. I think the way Apple solved the problem is very straightforward. So we steal it.
It's written considering that you won't probably scroll the body, because in the many designs I've seen for smartphones, scrolling a container allows you to have fixed headers and footers for Android < 4 without getting mad.
A word of warning: this code is really fresh and untested.
SEE DEMO AND CODE
CSS (extract)
#scrolling {
padding-top: 44px;
overflow: scroll;
-webkit-overflow-scroll: touch;
height: 100%;
}
.menu {
position: fixed;
right: 0;
font-size: 12px;
text-align: center;
display: inline-block;
z-index: 2;
top: 58px;
}
.list .divider {
position: -webkit-sticky; /* will stop the label when it reaches the header */
top: 44px;
}
HTML (extract)
<div id="scrolling">
<ul class="menu">
<li>A</li>
<li>B</li>
<li>C</li>
<!-- etc -->
</ul>
<ul class="list">
<li class="divider" id="a">A</li>
<li>Amelia Webster</li>
<li>Andrew WifKinson</li>
<!-- etc -->
Javascript (zepto/jquery)
$(function() {
$(window).on("touchstart touchmove mouseover click", ".menu a", function(e) {
e.preventDefault();
clearInterval(t);
var steps = 25;
var padding = 68;
var target = $( $(this).attr("href") ).next("li");
if ( target.length > 0 ) {
var scroller = $("#scrolling")[0];
var step = parseInt((target[0].offsetTop - padding - scroller.scrollTop)/steps);
var stepno = 0;
setInterval( function() {
if ( stepno++ <= steps ) {
scroller.scrollTop += step;
} else {
clearInterval(t)
}
}, 20);
};
});
});
It performs a basic check of link validity before attempting the scroll. You can change padding to your needs.
Also, you will notice that we are targeting the first element after the required target. This is because Safari seems to go nuts because of the sticky positioning.
This code uses jQuery/Zepto selectors for the sake of brevity and readability. But these libraries are not really needed to achieve the result. With just a little extra digitation you could easily go dependency-free.
http://codepen.io/frapporti/pen/GtaLD
You can use a toggleable sidebar like this one. Resize your browser to the width of the screen of a mobile phone to understand what I mean.
Then create a directive in angularjs to wrap jQuery's animate function to scroll to a specific part in the article. Like this:
angular.module('yourModule', [])
.directive('scrollTo', function() {
return {
restrict : 'EA',
link: function(scope , element, attr){
$('html, body').animate({
scrollTop: $( attr['href'] ).offset().top
}, 300);
}
};
});
where href will be an id of a specific section in the article. Then all you need to do is apply the directive to the links in the sidebar.
...
<li><a href="#section-1" scroll-to>Jump to section 1</a></li>
...
Hope this helps.
This might be what you're looking for http://www.designkode.com/alphascroll-jquery-mobile/
Haven't used it myself, but seems pretty simple to get going with.
I think something like this could work for you: http://codepen.io/aecend/pen/AsnIE. This is just a basic prototype I put together to answer but I could expand on the concept if needed. Basically, it creates a translucent bar on the right side of the screen, finds each of the headings for articles (which would need to be adapted to suit your needs) and places clickable/tappable anchors to jump to individual articles. When you click one, the page scrolls to that article. I have a few ideas to make this actually usable, but here's the proof of concept.
CSS
#scrollhelper {
position: fixed;
top: 0;
right: 0;
height: 100%;
width: 5%;
background-color: rgba(0,0,0,0.2);
overflow: hidden;
}
#scrollhelper .point {
position: absolute;
display: block;
width: 100%;
height: 10px;
margin: 0 auto;
background-color: rgba(0,0,255,0.5);
}
JavaScript
var articles;
function buildScrollHelp() {
var bodyHeight = $("body").height();
var viewHeight = window.innerHeight;
$("#scrollhelper").html("");
articles.each(function() {
var top = $(this).offset().top;
var element = document.createElement("a");
element.className = "point";
element.href = "#" + $(this).attr("id");
element.style.top = ((top / bodyHeight) * viewHeight) + "px";
$(element).on("click", function(e){
e.preventDefault();
$('html, body').animate({
scrollTop: $($(this).attr("href")).offset().top
}, 500);
});
$("#scrollhelper")[0].appendChild(element);
});
}
$(document).ready(function() {
articles = $("body").children("[id]");
$("body").append("<div id=\"scrollhelper\"></div>");
$(window).resize(function(){
buildScrollHelp();
});
buildScrollHelp();
});
Background:
Let's say you have a simple page which has a logo and a heading only and one paragraph
<img src="http://blog.stackoverflow.com/wp-content/uploads/StackExchangeLogo1.png">
<h1>Foo Bar</h1>
<p>ABC12345</p>
This is how that looks like
That page, obviously would not have vertical overflow / scroll bar for almost even tiny scale mobile devices, let alone computers.
Question
How can you bring that heading to the top left of the screen and move the logo out of focus unless someone scrolls up? Open to using any JavaScript library and any CSS framework
Attempts:
Tried using anchors but they only work if the page already had a scroll bar and anchor was out of focus.
Tried window.scrollTo but that also requires the page to have scroll already
Tried $("html, body").animate({ scrollTop: 90}, 100); but that also doesn't work when the page doesn't have overflow
Notes:
Please note that adding some extra <br/> to induce an overflow is not the way to go, it can be done that way but that's a very ordinary workaround
Why is it needed?
Its for a form for mobile devices, simple requirement is to take the first field of the form to top of the page and hide the logo (one can scroll up if they wish to see it) so it doesn't take attention away. Not using jQueryMobile for this particular task.
If you want the user to be able to scroll up and see the logo, then the logo must be within the top boundary of the body tag, because anything outside of that tag will not be viewable. This means you cannot use negative margins or offsetting like that. The only way to achieve this is to have the page scroll to the desired location that is within the top boundary of the body tag. You can set the time for this event to one millisecond, but there will still be a 'jump' in the page when it is loaded. So, the logic is: first make sure the page is long enough to scroll to the right place, then scroll there.
//Change the jQuery selectors accordingly
//The minimum height of the page must be 100% plus the height of the image
$('body').css('min-height',$(document).height() + $('img').height());
//Then scroll to that location with a one millisecond interval
$('html, body').animate({scrollTop: $('img').height() + 'px'}, 1);
View it here.
Alternatively, you can load the page without the image in the first place. Then your form field will be flush with the top of the document. Then you could create the element at the top and similarly scroll the page again. This is a round-a-bout way of doing the same thing though. And the page will still 'jump,' there is no way around that.
Only CSS and anchor link solution
With a pseudo element :
--- DEMO ---
First :
set : html,body{height:100%;}
Second :
Choose one of your existing tags. This tag mustn't have a relatively positioned parent (except if it is the body tag). Preferably the first element in the markup displayed after the logo. For your example it would be the h1 tag. And give it this CSS :
h1:before {
content:"";
position:absolute;
height:100%;
width:1px;
}
This creates an element as heigh as the viewport area. As it is displayed under the logo, the vertical scroll lenght is the same as the logo height.
Third :
Give the first element after logo an id (for this example I gave id="anchor").
Then you can use a link like this your_page_link#anchor and you will automaticaly scroll to the anchor (logo outside/above the viewport).
This works whatever height the logo is.
link to editable fiddle
Full code :
HTML
<img src="http://blog.stackoverflow.com/wp-content/uploads/StackExchangeLogo1.png">
<h1 id="anchor">Foo Bar</h1>
<p>ABC12345</p> Anchor link
CSS
html, body {
height:100%;
margin:0;
padding:0;
}
h1:before {
content:"";
position:absolute;
width:1px;
left:0;
height:100%;
}
You might need to add js functionality to hide the logo if user scrolls down but I guess following code will fullfill the first requirement.
Please see
<script src="js/jquery.js"></script>
<img id='logo' src="http://blog.stackoverflow.com/wp-content/uploads/StackExchangeLogo1.png" style="display:none">
<h1>Foo Bar</h1>
<p>ABC12345</p>
<script type="text/javascript">
var p = $( "p:first" );
var isScrolled=false;
/* For Firfox*/
$('html').on ('DOMMouseScroll', function (e) {
isScrolled = true;
if(p.scrollTop()==0 && isScrolled==true){
$('#logo').css('display','block');
}
});
/* For Chrome, IE, Opera and Safari: */
$('html').on ('mousewheel', function (e) {
isScrolled = true;
if(p.scrollTop()==0 && isScrolled==true){
$('#logo').css('display','block');
}
});
</script>
I have referred this question to find solution.
You could use touchmove event to detect swipe up or down. This is my example. You can try it on mobile device.
<style>
#logo {
position: absolute;
top: -100%;
-webkit-transition: top 0.5s;
-moz-transition: top 0.5s;
-ms-transition: top 0.5s;
-o-transition: top 0.5s;
transition: top 0.5s;
}
#logo.show {
top: 0;
}
</style>
<script>
var perY;
var y;
$(window).on('touchmove', function(e) {
e.preventDefault();
y = window.event.touches[0].pageY;
if(!perY)
perY = y;
else
{
if(y > perY)
$('#logo').addClass('show');
else
$('#logo').removeClass('show');
perY = null;
}
});
</script>
<img id="logo" src="http://blog.stackoverflow.com/wp-content/uploads/StackExchangeLogo1.png">
<h1>Foo Bar</h1>
<p>ABC12345</p>
This is the same problem i've encountered hiding the addressbar without the page overflowing. The only solution that fitted my needs was the following:
Set the min-height of the body to the viewportheight + your logo.
$('body').css('min-height', $(window).height() + 200);
This is a simple solution of getting the height of the contents to see if we can scroll to the part of the header, if not, we add height to the paragraph.
<img id="img" src="http://blog.stackoverflow.com/wp-content/uploads/StackExchangeLogo1.png" />
<h1 id="h" >Foo Bar</h1>
<p id="par" style="background:yellow;">
hello world
</p>
script:
function hola(){
var imgH = $("#img").outerHeight(true);
var titleH = $("#h").outerHeight(true);
var winH = $(window).height();
var parH = $('#par').outerHeight(true);
var contH = (imgH + titleH + parH);
var wishH = (imgH + winH);
console.log("wished height: " + wishH);
console.log("window height: " + winH);
console.log("content height: " + contH);
if(contH < wishH){
console.log("window is smaller than desired :(");
var newH = wishH - contH;
$("#par").height(parH + newH);
$(window).scrollTop(imgH);
}
}
Here is the working example:
http://jsfiddle.net/Uup62/1/
You may like this solution: http://jsfiddle.net/jy8pT/1/
HTML:
<div class="addScroll"></div>
<h1 class="logo"><img src="https://drupal.org/files/images/OQAAAI1PPrJY0nBALB7mkvju3mkQXqLmzMhxEjeb4gp8aujEUQcLfLyy-Sn4gZdkAas6-k8eYbQlGDE-GCjKfF5gIrUA15jOjFfLRv77VBd5t-WfZURdP9V3PdmT.png" height="100" alt="company logo"/></h1>
<h2>This is a sample page heading.</h2>
<p>This is a sample page text.</p>
JS:
function addScroll()
{
$(".addScroll").css({
"height": ($(window).height()+1) + "px",
"width": "100%"
});
}
$(document).ready(function(){
addScroll();
$(window).resize(function(){
addScroll();
});
$(window).scroll(function(){
if($(window).scrollTop() > 0)
{
$(".logo").animate({
marginTop: "-110px"
}, 500);
}
if($(window).scrollTop() == 0)
{
$(".logo").animate({
marginTop: "0"
}, 500);
}
});
});
CSS:
body
{
padding:0;
margin:0;
}
h1.logo
{
display:block;
margin:0 0 10px 0;
padding:0;
outline:0;
}
.addScroll
{
position:absolute;
display:block;
top:0;
left:0;
z-index:-1;
}
clicking the link the anchor is reached, but even if the parent element has overflow:hidden
it scrolls unnecessarily hiding the contents
<style>
div#x
{overflow:hidden;border-bottom:1px red solid;}
div#x > div
{border:1px red solid;padding:10px;float:left;width:33%;box-sizing:border-box;padding-bottom:10000px;margin-bottom:-10000px;}
</style>
<div id="x">
<div>go to<br><br>a</div>
<div>a<br><br><br><br>a</div>
<div>a<br><br><br><br><br><br><span id="test">go here</span></div>
</div>
demo: http://jsfiddle.net/aj8cX/5/
is there a way to fix this behavior?
This is as close as I could get, using table > table-cell:
http://jsfiddle.net/mikedidthis/AmNxf/
Would work well for static content, but for dynamic content it may cause some issues.
You could use some javascript trickery.
I am using jQuery, but you can use anything you want.
$('a[href="#test"]').on('click', function(){
var test_element = $('#test');
var scroll_top = test_element.scrollTop();
var max_height = test_element.parent().height();
if (scroll_top < max_height) { return false; }
else { return true; } //only scroll if the item is in view
});
You can use javascript to get elements of equal height:
var height = 0;
$.each($('#x div'),function(k,v){
if($(this).height() > height){
height = $(this).height();
}
});
$.each($('#x div'),function(){
$(this).height(height);
});
Fix your css like so:
div#x
{
overflow:visible;
height:10000px;
}
div#x div
{
border:1px red solid;
float:left;
width:33%;
box-sizing:border-box;
margin-right:-1px;
}
Working example: http://jsfiddle.net/aj8cX/6/