简体   繁体   中英

Smooth scrolling with timer in HTML

Synopsis: The main idea behind this is to auto smooth scroll to the testimonials section of my html after a certain amount of time.

Achieved so far: I'm able to scroll to the testimonials section of the page after X seconds without any problems using a simple script in my main index.html page. The script code is given below.

Auto scroll in the page after 5secs

<script>
  setTimeout(function(){
    window.location.hash = '#testimonials';
  },5000);
</script>

Problem facing: I've smooth scrolling in the entire page, but for the timer scrolling in my page, I'm unable to use smooth scroll. The uncertain transition is looking awkward, hence, I want to make it smooth scroll. Also, I want this to happen only for the first time on page loading, ie, if any operation is done in the page, this will not happen if visited index.html again.

TIA guys!

 function goTo(selector, timeout, cb) { var $el = $(selector); if (!$el[0]) return; var $par = $el.parent(); if ($par.is("body")) $par = $("html, body"); setTimeout(() => { $par.stop().animate({scrollTop: $el.offset().top}, 1000, cb && cb.call($el[0])); }, timeout || 0); } // USE LIKE: goTo("#testimonials", 3000, function() { // You can use `this` to reference #testimonials! yey $(this).append("<br>Going to #contact in 3sec!"); goTo("#contact", 3000); }); // Alternatively, without using callbacks you can do // goTo("#testimonials", 3000); // goTo("#contact", 6000); // Reuse function for elements click! $("[href^='#']").on("click", function(e) { e.preventDefault(); goTo($(this).attr("href")); }); 
 /*QuickReset*/ *{margin:0;box-sizing:border-box;} html,body{height:100%;font:14px/1.4 sans-serif;} article { height: 150vh; } 
 <article style="background:#0bf;" id="top">WELCOME (wait 3 sec)</article> <article style="background:#f0b;" id="about">ABOUT</article> <article style="background:#b0f;" id="work">OUR WORK</article> <article style="background:#0fb;" id="testimonials">TESTIMONIALS</article> <article style="background:#fb0;" id="contact"> CONTACT <a href="#top">TO TOP</a> </article> <script src="//code.jquery.com/jquery-3.1.0.js"></script> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM