How to Animate Scroll to Top JavaScript - javascript

I have got 2 websites with the same function. It works on one of the websites, doesn't work on the other.
script.js:
function scrollToTop(){
var timerHandle = setInterval(function() {
if (document.body.scrollTop != 0 || document.documentElement.scrollTop != 0)
window.scrollBy(0,-50); else clearInterval(timerHandle); },10);
}
HTML
<ul class="footer-navigation">
<li><a class="back" id="backtoTop" onclick="scrollToTop();return false;"href="#">↑Back to Top</a></li>
<li><a class="home" href="#home">Home</a></li>
<li><a class="about" href="#about">About</a></li>
<li><a class="contact" href="#contact">Contact</a></li>
</ul>
It doesn't hit any error but it seems as though it is "counting". When I console.log it there's a number in the console next to the logged counting but function never executes.
Thanks

Try this:
function scrollToTop(){
window.scrollTo({top: 0, behavior: 'smooth'});
}
<div style="height: 150vh">
scroll down
</div>
<ul class="footer-navigation">
<li><a class="back" id="backtoTop" onclick="scrollToTop();return false;"href="#">↑Back to Top</a></li>
<li><a class="home" href="#home">Home</a></li>
<li><a class="about" href="#about">About</a></li>
<li><a class="contact" href="#contact">Contact</a></li>
</ul>

I would say that you shouldn't scroll via a setInterval but through requestAnimationFrame to avoid jankiness in the scroll. A simple solution to your problem would also to use CSS to make your scrolling smooth. However, this affects all scrolling.
function scrollToTop(){
window.scrollTo(0, 0);
}
html {
scroll-behavior: smooth;
}
<div style="height: 150vh">
scroll down
</div>
<ul class="footer-navigation">
<li><a class="back" id="backtoTop" onclick="scrollToTop()"href="#">↑Back to Top</a></li>
<li><a class="home" href="#home">Home</a></li>
<li><a class="about" href="#about">About</a></li>
<li><a class="contact" href="#contact">Contact</a></li>
</ul>
More about requestforanimationframe:
https://stackoverflow.com/a/46072227/5526624

To complete the previous answers, we can use the following code to the CSS so as not to forget accessibility ;
#media (prefers-reduced-motion: reduce) {
html {
scroll-behavior: auto;
}
}
Indeed, there are people who have disorders of the vestibular systems and who have configured their browser to reduce animations and movements

(function($){
'use strcit';
$.ScrollUpToTop = function(options){
// Default options
options = $.extend({}, options);
// Variables
var $btnScroll = $("<button id=\"ScrollUpToTop\">^</button>").hide();
var $body = $(document.body);
// insert scroll up to top button
$($body).append($btnScroll);
// attach click event on button
$($btnScroll).click(function(e){
e.preventDefault();
$($body).animate(
{scrollTop:0},
800
);
});
$(window).scroll(function(){
if( $(window).scrollTop() > 0) {
$($btnScroll).fadeIn();
} else {
$($btnScroll).fadeOut();
}
});
};
$.ScrollUpToTop();
})(jQuery);
Please follow this link.
https://www.jqueryscript.net/demo/Super-Simple-Scroll-Up-To-Top-Plugin-with-jQuery/
and you can also get reference from using source.
view-source:https://www.jqueryscript.net/demo/Super-Simple-Scroll-Up-To-Top-Plugin-with-jQuery/

use this bro in pure javascript no css needed : window.scrollTo({ top: 0, behavior: "smooth" })

Related

Scroll to javascript

So this is what I have as my top nav bar. I'm using this along with jquery
<nav>
<div class="brand">BRAND</div>
<ul>
<li><a id="home" href="#home">Home</a></li>
<li><a id="about" href="#about">About</a></li>
<li><a id="buy" href="#buy">Buy</a></li>
<li><a id="contact" href="#contact">Contact</a></li>
<li><a id="login" class="active" href="#">Log In</a></li>
</ul>
</nav>
and i'm trying to use this line of code to have it when clicked on one of the options on my nav bar to scroll to that element
$("nav a").on("click", function(e) {
e.preventDefault();
var section = $(this).attr("href");
$("html, body").animate({
scrollTop: $(section).offset().top
}, 850);
});
but it isn't working?
You have to put the id to thelement you want to scroll to not the link itself
$("nav a").on("click", function(e) {
e.preventDefault();
var section = $(this).attr("href");
$("html, body").animate({
scrollTop: $(section).offset().top
}, 850);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav>
<div class="brand">BRAND</div>
<ul>
<li>Home</li>
<li>About</li>
<li>Buy</li>
<li>Contact</li>
<li><a class="active" href="#">Log In</a></li>
</ul>
</nav>
<br/><br/><br/><br/><br/><br/><br/><br/><br/>
<div id="home">
example
</div>
You've put the ids on the wrong elements. Each of your links is set to target itself -- so the browser scrolls to the link that was just clicked, which is already visible.
Place id="…" on the element that you want to scroll to, not the link.

Href tag not working in chrome but working in other browser

I'm working on designing website but facing a issue that href # tags are not working in chrome but working in firefox
<ul class="navigation" style="margin-top: 75px;">
<li><a class="scroll-to" href="#section-1">Home</a></li>
<li><a class="scroll-to" href="#section-2">About Us</a></li>
<li><a class="scroll-to" href="#section-4">Products</a></li>
<li><a class="scroll-to" href="#section-5">Clients</a></li>
<li><a class="scroll-to" href="#section-6">Team</a></li>
<li><a class="scroll-to" href="#section-7">Contact Us</a></li>
</ul>
<section id="section-1" class="banner-container color-light center nav-trigger">
I am not sure where its going wrong
The following works fine for me in Chrome 62. Are you closing your section tag? Are you sure there is enough height that it would actually scroll?
section {
padding: 100px;
border: 1px solid blue;
}
<ul>
<li>Home</li>
<li>About Us</li>
<li>Products</li>
<li>Clients</li>
<li>Team</li>
<li>Contact Us</li>
</ul>
<section id="section-1">Home</section>
<section id="section-2">About Us</section>
<section id="section-4">Products</section>
<section id="section-5">Clients</section>
<section id="section-6">Team</section>
<section id="section-7">Contact Us</section>
You can try follow this.
https://www.gregoryvarghese.com/chrome-anchor-link-not-working-fix/
$(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;
}
}
});
});
Make sure you have enough height for each div so that page can scroll. Without page scroll you can't see changes, because nothing wrong with your code.
<ul>
<li>Home</li>
<li>About Us</li>
<li>Products</li>
<li>Clients</li>
<li>Team</li>
<li>Contact Us</li>
</ul>
<section style="height:500px" id="section-1">Home</section>
<section style="height:500px" id="section-2">About Us</section>
<section style="height:500px" id="section-4">Products</section>
<section style="height:500px" id="section-5">Clients</section>
<section style="height:500px" id="section-6">Team</section>
<section style="height:500px" id="section-7">Contact Us</section>
I guess its a bug in certain versions of Chrome, this workaround did the trick for me, good luck! -
$(document).ready(function () {
var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
if (window.location.hash && isChrome) {
setTimeout(function () {
var hash = window.location.hash;
window.location.hash = "";
window.location.hash = hash;
}, 300);
}
});
For me, it was the href that redirected to pages with hashtags, so I did this workaround:
$('body').on('click', 'a[href*="#"]:not([href="#"])', function(e) {
if($(this).attr('href').indexOf('http') > -1 && /chrome/i.test( navigator.userAgent) ){
e.preventDefault();
window.location.href = $(this).attr('href');
window.location.reload();
return false;
}
});

Toggle classes onlick from multiple instances

So I ran into a problem regarding my toggle function. In my current case I would like to be able to turn parts of the web-based interface on and off (display:none and block). I got it to work from one of the windows but the snag I hit was when I added multiple calls to the same functions. I reverted from using getElementById and used getElementsByClass instead. This caused no problems as far as I know of. When I added the second menu however things started to malfunction.
I'll paste my code and a jsFiddle down below.
My goal is to make the onclick on the <li> toggle the other <li> and toggle the map/cesium at the same time.
HTML
<div id="map">
<nav id="primary_nav_wrap">
<ul>
<li>=
<ul>
<li><a class="buttonMap" href="#" onclick="toggleMap('none')">Toggle Map</a></li>
<li><a class="buttonMap2" href="#" onclick="toggleMap('block')">Toggle Map</a></li>
<li><a class="buttonCesium" href="#" onclick="toggleCesium('none')">Toggle Cesium</a></li>
<li><a class="buttonCesium2" href="#" onclick="toggleCesium('none')">Toggle Cesium</a></li>
</ul>
</li>
</ul>
</nav>
</div>
<div id="cesium">
<nav id="primary_nav_wrap">
<ul>
<li>=
<ul>
<li><a class="buttonMap" href="#" onclick="toggleMap('none')">Toggle Map</a></li>
<li><a class="buttonMap2" href="#" onclick="toggleMap('block')">Toggle Map</a></li>
<li><a class="buttonCesium" href="#" onclick="toggleCesium('none')">Toggle Cesium</a></li>
<li><a class="buttonCesium2" href="#" onclick="toggleCesium('block')">Toggle Cesium</a></li>
</ul>
</li>
</ul>
</nav>
CSS (minimal but so JsFiddle gets the point across)
#map{
height:100px;
width:100px;
background-color:red;
}
#cesium{
height:100px;
width:100px;
background-color:blue;
}
JS
function toggleMap(display) {
var elem = document.getElementById("map");
var buttonMap = document.getElementsByClassName("buttonMap");
elem.style.display = display;
buttonMap.style.display = display;
if (buttonMap.style.display === 'none'){
buttonMap2.style.display = 'block';
}
else if (buttonMap.style.display === 'block'){
buttonMap2.style.display = 'none';
}
};
function toggleCesium(display) {
var elem = document.getElementById("cesium");
var buttonCesium = document.getElementsByClassName("buttonCesium");
elem.style.display = display;
buttonCesium.style.display = display;
if (buttonCesium.style.display === 'none'){
buttonCesium2.style.display = 'block';
}
else if (buttonCesium.style.display === 'block'){
buttonCesium2.style.display = 'none';
}
};
In the JsFiddle, the colored blocks should disappear.
Any help is appreciated!
(PS! We can safely assume users will be using up-to-date browsers)
https://jsfiddle.net/rz4wu4qd/18/
Somewhat working solution as mentioned in comments.
getElementsByClassName returns an array, so you need to iterate through it, for example with a for loop.

Trigger div on pageload

I have been trying to set the scroll of my page to a certain div. Kindly let me know how can i do that. Following is my code in which each each option in li moves to certain div . I tried this $("#header3").click(); in doucument.ready function but it didnot work.
Kindly help!
<ul id="navigation">
<LI><A class="home selected-lice"href="#header">Home</A></LI>
<LI>Partners</LI>
<LI><A class="about" href="#header5">About Us</A></LI>
<LI><A class="contact" href="#header6">Contact Us</A></LI>
</ul><!-- end of #navigation -->
Alternatively you can use this to scroll to specific element on page load with animation:
$(function(){
$('html, body').animate({ scrollTop: $("#header1").offset().top });
});
check this link:
http://css-tricks.com/snippets/jquery/smooth-scrolling/
or try to overwrite the usual anchor behavior with some scrolling. Like this:
$(function(){
$('a[href^=#]').click(function(e){
var name = $(this).attr('href').substr(1);
var pos = $('a[name='+name+']').offset();
$('body').animate({ scrollTop: pos.top });
e.preventDefault();
});
});

Collpasible menu needs all header needs to be closed on initial loading

I have a sidebar with collapsible menu it works fine but all the values come expanded the initial loading time.I want it to be closed on load and toggled thereafter.
Here is the jquery used
// Sidebar Toggle
var fluid = {
Toggle : function(){
var default_hide = {"grid": true };
$.each(
["pagesnav", "commentsnav", "userssnav", "imagesnav"],
function() {
var el = $("#" + (this == 'accordon' ? 'accordion-block' : this) );
if (default_hide[this]) {
el.hide();
$("[id='toggle-"+this+"']").addClass("hidden");
}
$("[id='toggle-"+this+"']")
.bind("click", function(e) {
if ($(this).hasClass('hidden')){
$(this).removeClass('hidden').addClass('visible');
el.slideDown();
} else {
$(this).removeClass('visible').addClass('hidden');
el.slideUp();
}
e.preventDefault();
});
}
);
}
}
jQuery(function ($) {
if($("[id^='toggle']").length){fluid.Toggle();}
});
here is the html
<span class="ul-header"><a id="toggle-pagesnav" href="#" class="toggle visible">Content</a></span>
<ul id="pagesnav">
<li><a class="icn_manage_pages" href="#">Manage Pages</a></li>
<li><a class="icn_add_pages" href="#">Add Pages</a></li>
<li><a class="icn_edit_pages" href="#">Edit Pages</a></li>
<li><a class="icn_delete_pages" href="#">Delete Pages</a></li>
</ul>
<!-- End Content Nav -->
<!-- Start Comments Nav -->
<span class="ul-header"><a id="toggle-commentsnav" href="#" class="toggle visible">Comments</a></span>
<ul id="commentsnav">
<li><a class="icn_manage_comments" href="#">Manage Comments</a></li>
<li><a class="icn_add_comments" href="#">Add Comments</a></li>
<li><a class="icn_edit_comments" href="#">Edit Comments</a></li>
<li><a class="icn_delete_comments" href="#">Delete Comments</a></li>
</ul>
here is the css used
.toggle {
display:block;
}
.ul-header a.visible {
background:url('../img/icons/small/toggle_close.png') no-repeat scroll 97% 50%;
}
.ul-header a.hidden {
background:url('../img/icons/small/toggle_open.png') no-repeat scroll 97% 50%;
}
Please help.
This is the variable which is checked against to see if a block has to be hidden or not.
var default_hide = {"grid": true };
Change it to
var default_hide = {"pagesnav": true, "commentsnav": true, "userssnav": true, "imagesnav": true}
and it should work.
Or you can remove this if:
if (default_hide[this])
I'd say the most efficient and painfree way to have them all initially collapsed is to specify them like that initially in the HTML. So add class="hidden" to each of your nav ul-s.

Categories