Scrolling instead of anchoring [duplicate] - javascript

I have a couple of hyperlinks on my page. A FAQ that users will read when they visit my help section.
Using Anchor links, I can make the page scroll towards the anchor and guide the users there.
Is there a way to make that scrolling smooth?
But notice that he's using a custom JavaScript library. Maybe jQuery offers somethings like this baked in?

Update April 2018: There's now a native way to do this:
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
anchor.addEventListener('click', function (e) {
e.preventDefault();
document.querySelector(this.getAttribute('href')).scrollIntoView({
behavior: 'smooth'
});
});
});
This is currently only supported in the most bleeding edge browsers.
For older browser support, you can use this jQuery technique:
$(document).on('click', 'a[href^="#"]', function (event) {
event.preventDefault();
$('html, body').animate({
scrollTop: $($.attr(this, 'href')).offset().top
}, 500);
});
And here's the fiddle: http://jsfiddle.net/9SDLw/
If your target element does not have an ID, and you're linking to it by its name, use this:
$('a[href^="#"]').click(function () {
$('html, body').animate({
scrollTop: $('[name="' + $.attr(this, 'href').substr(1) + '"]').offset().top
}, 500);
return false;
});
For increased performance, you should cache that $('html, body') selector, so that it doesn't run every single time an anchor is clicked:
var $root = $('html, body');
$('a[href^="#"]').click(function () {
$root.animate({
scrollTop: $( $.attr(this, 'href') ).offset().top
}, 500);
return false;
});
If you want the URL to be updated, do it within the animate callback:
var $root = $('html, body');
$('a[href^="#"]').click(function() {
var href = $.attr(this, 'href');
$root.animate({
scrollTop: $(href).offset().top
}, 500, function () {
window.location.hash = href;
});
return false;
});

The new hotness in CSS3. This is a lot easier than every method listed on this page and requires no Javascript. Just enter the below code into you css and all of a sudden links point to locations inside you own page will have a smooth scrolling animation.
html{scroll-behavior:smooth}
After that any links pointed towards a div will smoothly glide over to those sections.
Section1
Edit: For those confused about the above a tag. Basically it's a link that's clickable. You can then have another div tag somewhere in your web page like
<div id="section">content</div>
In this regard the a link will be clickable and will go to whatever #section is, in this case it's our div we called section.
BTW, I spent hours trying to get this to work. Found the solution in some obscure comments section. It was buggy and wouldn't work in some tags. Didn't work in the body. It finally worked when I put it in html{} in the CSS file.

The correct syntax is:
//Smooth scrolling with links
$('a[href^=\\#]').on('click', function(event){
event.preventDefault();
$('html,body').animate({scrollTop:$(this.hash).offset().top}, 500);
});
// Smooth scrolling when the document is loaded and ready
$(document).ready(function(){
$('html,body').animate({scrollTop:$(location.hash).offset().‌​top}, 500);
});
Simplifying: DRY
function smoothScrollingTo(target){
$('html,body').animate({scrollTop:$(target).offset().​top}, 500);
}
$('a[href^=\\#]').on('click', function(event){
event.preventDefault();
smoothScrollingTo(this.hash);
});
$(document).ready(function(){
smoothScrollingTo(location.hash);
});
Explanation of href^=\\#:
^ means it matches what contains # char. Thus only match anchors to make sure it's a link for the same page (Thanks Peter Wong for your suggestion).
\\ is because the # is a special char in css selector, so we have to escape it.

Only CSS
html {
scroll-behavior: smooth;
}
All you need to add only this. Now your internal links scrolling behavior will be smooth like a stream-flow.
Programmatically: Something extra and advanced
// Scroll to specific values
// window.scrollTo or window.scroll
window.scroll({
top: 1000,
left: 0,
behavior: 'smooth'
});
// Scroll certain amounts from current position
window.scrollBy({
top: 250, // could be negative value
left: 0,
behavior: 'smooth'
});
// Scroll to a certain element
document.getElementById('el').scrollIntoView({
behavior: 'smooth'
})
Note: All latest browsers (Opera, Chrome, Firefox etc) supports this feature.
for detail understanding, read this article

I'm surprised no one has posted a native solution that also takes care of updating the browser location hash to match. Here it is:
let anchorlinks = document.querySelectorAll('a[href^="#"]')
 
for (let item of anchorlinks) { // relitere
    item.addEventListener('click', (e)=> {
        let hashval = item.getAttribute('href')
        let target = document.querySelector(hashval)
        target.scrollIntoView({
            behavior: 'smooth',
            block: 'start'
        })
        history.pushState(null, null, hashval)
        e.preventDefault()
    })
}
See tutorial: http://www.javascriptkit.com/javatutors/scrolling-html-bookmark-javascript.shtml
For sites with sticky headers, scroll-padding-top CSS can be used to provide an offset.

$('a[href*=#]').click(function(event){
$('html, body').animate({
scrollTop: $( $.attr(this, 'href') ).offset().top
}, 500);
event.preventDefault();
});
this worked perfect for me

No need any js just use scroll-behavior: smooth at html tag Thats it
html{
scroll-behavior: smooth;
}

I suggest you to make this generic code :
$('a[href^="#"]').click(function(){
var the_id = $(this).attr("href");
$('html, body').animate({
scrollTop:$(the_id).offset().top
}, 'slow');
return false;});
You can see a very good article here : jquery-effet-smooth-scroll-defilement-fluide

There are already a lot of good answers here - however they are all missing the fact that empty anchors have to be excluded. Otherwise those scripts generate JavaScript errors as soon as an empty anchor is clicked.
In my opinion the correct answer is like this:
$('a[href*=\\#]:not([href$=\\#])').click(function() {
event.preventDefault();
$('html, body').animate({
scrollTop: $($.attr(this, 'href')).offset().top
}, 500);
});

There is native support for smooth scrolling on hash id scrolls.
html {
scroll-behavior: smooth;
}
You can take a look: https://www.w3schools.com/howto/howto_css_smooth_scroll.asp#section2

$(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;
}
}
});
});
Official:
http://css-tricks.com/snippets/jquery/smooth-scrolling/

Using JQuery:
$('a[href*=#]').click(function(){
$('html, body').animate({
scrollTop: $( $.attr(this, 'href') ).offset().top
}, 500);
return false;
});

For a more comprehensive list of methods for smooth scrolling, see my answer here.
You can use window.scroll() with behavior: smooth and top set to the anchor tag's offset top which ensures that the anchor tag will be at the top of the viewport.
document.querySelectorAll('a[href^="#"]').forEach(a => {
a.addEventListener('click', function (e) {
e.preventDefault();
var href = this.getAttribute("href");
var elem = document.querySelector(href)||document.querySelector("a[name="+href.substring(1, href.length)+"]");
//gets Element with an id of the link's href
//or an anchor tag with a name attribute of the href of the link without the #
window.scroll({
top: elem.offsetTop,
left: 0,
behavior: 'smooth'
});
//if you want to add the hash to window.location.hash
//you will need to use setTimeout to prevent losing the smooth scrolling behavior
//the following code will work for that purpose
/*setTimeout(function(){
window.location.hash = this.hash;
}, 2000); */
});
});
Demo:
a, a:visited{
color: blue;
}
section{
margin: 500px 0px;
text-align: center;
}
Section 1
<br/>
Section 2
<br/>
Section 3
<br/>
Section 4
<section id="section1">
<b style="font-size: 2em;">Section 1</b>
<p>Lorem ipsum dolor sit amet, et vis laudem utroque, iusto forensibus neglegentur eu duo. Eu pro fuisset salutandi philosophia, discere persecuti qui te. Eos ad quodsi dissentias, ei odio viris signiferumque mei. Putent iuvaret perpetua nec eu. Has no ornatus vivendum. Adhuc nonumes ex vim, in suas rebum graecis mei, usu ad causae recusabo. Idque vituperata vel ea.
Veri verterem pro ex. Ad error omnes est, id sit lorem legendos. Eos vidit ullum ne, tale tantas omittam est ut. Nobis maiorum efficiendi eu mei. Eos et debet placerat signiferumque. Per eu propriae electram.
Impetus percipit menandri te ius, mea ne stet posse fabellas. Aliquid corrumpit vel no, mei in diam praesent contentiones. Qui veniam suscipit probatus ex. No autem homero perfecto quo, eos choro facilis ut. Te quo cibo interesset. Vel verear praesent in, menandri deserunt ad his.
Labore admodum consetetur has et. Possit facilisi eu sed, lorem iriure eum id, pri ei consul necessitatibus. Est te iusto epicuri. Vis no graece putent mentitum, rebum facete offendit nec in. In duis vivendo sed, vel id enim voluptatibus. Velit sanctus ne mel, quem sumo suavitate mel cu, mea ea nullam feugiat.
Tincidunt suscipiantur no pro. Vel ut novum mucius molestie, ut tale ipsum intellegebat mei, mazim accumsan voluptaria ea nam. Posidonium theophrastus ut sea, stet viris hendrerit pro ex, sonet mentitum ne quo. Vim duis feugiat ex, nec eu probo doming persecuti. Velit zril nam in, est commodo splendide id. Et aperiri fuisset iracundia usu. Eu nec iusto audire repudiare.<p/>
<section>
<section id="section2">
<b style="font-size: 2em;">Section 2</b>
<p>Lorem ipsum dolor sit amet, et vis laudem utroque, iusto forensibus neglegentur eu duo. Eu pro fuisset salutandi philosophia, discere persecuti qui te. Eos ad quodsi dissentias, ei odio viris signiferumque mei. Putent iuvaret perpetua nec eu. Has no ornatus vivendum. Adhuc nonumes ex vim, in suas rebum graecis mei, usu ad causae recusabo. Idque vituperata vel ea.
Veri verterem pro ex. Ad error omnes est, id sit lorem legendos. Eos vidit ullum ne, tale tantas omittam est ut. Nobis maiorum efficiendi eu mei. Eos et debet placerat signiferumque. Per eu propriae electram.
Impetus percipit menandri te ius, mea ne stet posse fabellas. Aliquid corrumpit vel no, mei in diam praesent contentiones. Qui veniam suscipit probatus ex. No autem homero perfecto quo, eos choro facilis ut. Te quo cibo interesset. Vel verear praesent in, menandri deserunt ad his.
Labore admodum consetetur has et. Possit facilisi eu sed, lorem iriure eum id, pri ei consul necessitatibus. Est te iusto epicuri. Vis no graece putent mentitum, rebum facete offendit nec in. In duis vivendo sed, vel id enim voluptatibus. Velit sanctus ne mel, quem sumo suavitate mel cu, mea ea nullam feugiat.
Tincidunt suscipiantur no pro. Vel ut novum mucius molestie, ut tale ipsum intellegebat mei, mazim accumsan voluptaria ea nam. Posidonium theophrastus ut sea, stet viris hendrerit pro ex, sonet mentitum ne quo. Vim duis feugiat ex, nec eu probo doming persecuti. Velit zril nam in, est commodo splendide id. Et aperiri fuisset iracundia usu. Eu nec iusto audire repudiare.</p>
<section>
<section id="section3">
<b style="font-size: 2em;">Section 3</b>
<p>
Lorem ipsum dolor sit amet, et vis laudem utroque, iusto forensibus neglegentur eu duo. Eu pro fuisset salutandi philosophia, discere persecuti qui te. Eos ad quodsi dissentias, ei odio viris signiferumque mei. Putent iuvaret perpetua nec eu. Has no ornatus vivendum. Adhuc nonumes ex vim, in suas rebum graecis mei, usu ad causae recusabo. Idque vituperata vel ea.
Veri verterem pro ex. Ad error omnes est, id sit lorem legendos. Eos vidit ullum ne, tale tantas omittam est ut. Nobis maiorum efficiendi eu mei. Eos et debet placerat signiferumque. Per eu propriae electram.
Impetus percipit menandri te ius, mea ne stet posse fabellas. Aliquid corrumpit vel no, mei in diam praesent contentiones. Qui veniam suscipit probatus ex. No autem homero perfecto quo, eos choro facilis ut. Te quo cibo interesset. Vel verear praesent in, menandri deserunt ad his.
Labore admodum consetetur has et. Possit facilisi eu sed, lorem iriure eum id, pri ei consul necessitatibus. Est te iusto epicuri. Vis no graece putent mentitum, rebum facete offendit nec in. In duis vivendo sed, vel id enim voluptatibus. Velit sanctus ne mel, quem sumo suavitate mel cu, mea ea nullam feugiat.
Tincidunt suscipiantur no pro. Vel ut novum mucius molestie, ut tale ipsum intellegebat mei, mazim accumsan voluptaria ea nam. Posidonium theophrastus ut sea, stet viris hendrerit pro ex, sonet mentitum ne quo. Vim duis feugiat ex, nec eu probo doming persecuti. Velit zril nam in, est commodo splendide id. Et aperiri fuisset iracundia usu. Eu nec iusto audire repudiare.</p>
<section>
<a style="margin: 500px 0px; color: initial;" name="section4">
<b style="font-size: 2em;">Section 4 <i>(this is an anchor tag, not a section)</i></b>
</a>
<p>
Lorem ipsum dolor sit amet, et vis laudem utroque, iusto forensibus neglegentur eu duo. Eu pro fuisset salutandi philosophia, discere persecuti qui te. Eos ad quodsi dissentias, ei odio viris signiferumque mei. Putent iuvaret perpetua nec eu. Has no ornatus vivendum. Adhuc nonumes ex vim, in suas rebum graecis mei, usu ad causae recusabo. Idque vituperata vel ea.
Veri verterem pro ex. Ad error omnes est, id sit lorem legendos. Eos vidit ullum ne, tale tantas omittam est ut. Nobis maiorum efficiendi eu mei. Eos et debet placerat signiferumque. Per eu propriae electram.
Impetus percipit menandri te ius, mea ne stet posse fabellas. Aliquid corrumpit vel no, mei in diam praesent contentiones. Qui veniam suscipit probatus ex. No autem homero perfecto quo, eos choro facilis ut. Te quo cibo interesset. Vel verear praesent in, menandri deserunt ad his.
Labore admodum consetetur has et. Possit facilisi eu sed, lorem iriure eum id, pri ei consul necessitatibus. Est te iusto epicuri. Vis no graece putent mentitum, rebum facete offendit nec in. In duis vivendo sed, vel id enim voluptatibus. Velit sanctus ne mel, quem sumo suavitate mel cu, mea ea nullam feugiat.
Tincidunt suscipiantur no pro. Vel ut novum mucius molestie, ut tale ipsum intellegebat mei, mazim accumsan voluptaria ea nam. Posidonium theophrastus ut sea, stet viris hendrerit pro ex, sonet mentitum ne quo. Vim duis feugiat ex, nec eu probo doming persecuti. Velit zril nam in, est commodo splendide id. Et aperiri fuisset iracundia usu. Eu nec iusto audire repudiare.</p>
<script>
document.querySelectorAll('a[href^="#"]').forEach(a => {
a.addEventListener('click', function (e) {
e.preventDefault();
var href = this.getAttribute("href");
var elem = document.querySelector(href)||document.querySelector("a[name="+href.substring(1, href.length)+"]");
window.scroll({
top: elem.offsetTop,
left: 0,
behavior: 'smooth'
});
});
});
</script>
You can just set the CSS property scroll-behavior to smooth (which most modern browsers support) which obviates the need for Javascript.
html, body{
scroll-behavior: smooth;
}
a, a:visited{
color: blue;
}
section{
margin: 500px 0px;
text-align: center;
}
Section 1
<br/>
Section 2
<br/>
Section 3
<br/>
Section 4
<section id="section1">
<b style="font-size: 2em;">Section 1</b>
<p>Lorem ipsum dolor sit amet, et vis laudem utroque, iusto forensibus neglegentur eu duo. Eu pro fuisset salutandi philosophia, discere persecuti qui te. Eos ad quodsi dissentias, ei odio viris signiferumque mei. Putent iuvaret perpetua nec eu. Has no ornatus vivendum. Adhuc nonumes ex vim, in suas rebum graecis mei, usu ad causae recusabo. Idque vituperata vel ea.
Veri verterem pro ex. Ad error omnes est, id sit lorem legendos. Eos vidit ullum ne, tale tantas omittam est ut. Nobis maiorum efficiendi eu mei. Eos et debet placerat signiferumque. Per eu propriae electram.
Impetus percipit menandri te ius, mea ne stet posse fabellas. Aliquid corrumpit vel no, mei in diam praesent contentiones. Qui veniam suscipit probatus ex. No autem homero perfecto quo, eos choro facilis ut. Te quo cibo interesset. Vel verear praesent in, menandri deserunt ad his.
Labore admodum consetetur has et. Possit facilisi eu sed, lorem iriure eum id, pri ei consul necessitatibus. Est te iusto epicuri. Vis no graece putent mentitum, rebum facete offendit nec in. In duis vivendo sed, vel id enim voluptatibus. Velit sanctus ne mel, quem sumo suavitate mel cu, mea ea nullam feugiat.
Tincidunt suscipiantur no pro. Vel ut novum mucius molestie, ut tale ipsum intellegebat mei, mazim accumsan voluptaria ea nam. Posidonium theophrastus ut sea, stet viris hendrerit pro ex, sonet mentitum ne quo. Vim duis feugiat ex, nec eu probo doming persecuti. Velit zril nam in, est commodo splendide id. Et aperiri fuisset iracundia usu. Eu nec iusto audire repudiare.<p/>
<section>
<section id="section2">
<b style="font-size: 2em;">Section 2</b>
<p>Lorem ipsum dolor sit amet, et vis laudem utroque, iusto forensibus neglegentur eu duo. Eu pro fuisset salutandi philosophia, discere persecuti qui te. Eos ad quodsi dissentias, ei odio viris signiferumque mei. Putent iuvaret perpetua nec eu. Has no ornatus vivendum. Adhuc nonumes ex vim, in suas rebum graecis mei, usu ad causae recusabo. Idque vituperata vel ea.
Veri verterem pro ex. Ad error omnes est, id sit lorem legendos. Eos vidit ullum ne, tale tantas omittam est ut. Nobis maiorum efficiendi eu mei. Eos et debet placerat signiferumque. Per eu propriae electram.
Impetus percipit menandri te ius, mea ne stet posse fabellas. Aliquid corrumpit vel no, mei in diam praesent contentiones. Qui veniam suscipit probatus ex. No autem homero perfecto quo, eos choro facilis ut. Te quo cibo interesset. Vel verear praesent in, menandri deserunt ad his.
Labore admodum consetetur has et. Possit facilisi eu sed, lorem iriure eum id, pri ei consul necessitatibus. Est te iusto epicuri. Vis no graece putent mentitum, rebum facete offendit nec in. In duis vivendo sed, vel id enim voluptatibus. Velit sanctus ne mel, quem sumo suavitate mel cu, mea ea nullam feugiat.
Tincidunt suscipiantur no pro. Vel ut novum mucius molestie, ut tale ipsum intellegebat mei, mazim accumsan voluptaria ea nam. Posidonium theophrastus ut sea, stet viris hendrerit pro ex, sonet mentitum ne quo. Vim duis feugiat ex, nec eu probo doming persecuti. Velit zril nam in, est commodo splendide id. Et aperiri fuisset iracundia usu. Eu nec iusto audire repudiare.</p>
<section>
<section id="section3">
<b style="font-size: 2em;">Section 3</b>
<p>
Lorem ipsum dolor sit amet, et vis laudem utroque, iusto forensibus neglegentur eu duo. Eu pro fuisset salutandi philosophia, discere persecuti qui te. Eos ad quodsi dissentias, ei odio viris signiferumque mei. Putent iuvaret perpetua nec eu. Has no ornatus vivendum. Adhuc nonumes ex vim, in suas rebum graecis mei, usu ad causae recusabo. Idque vituperata vel ea.
Veri verterem pro ex. Ad error omnes est, id sit lorem legendos. Eos vidit ullum ne, tale tantas omittam est ut. Nobis maiorum efficiendi eu mei. Eos et debet placerat signiferumque. Per eu propriae electram.
Impetus percipit menandri te ius, mea ne stet posse fabellas. Aliquid corrumpit vel no, mei in diam praesent contentiones. Qui veniam suscipit probatus ex. No autem homero perfecto quo, eos choro facilis ut. Te quo cibo interesset. Vel verear praesent in, menandri deserunt ad his.
Labore admodum consetetur has et. Possit facilisi eu sed, lorem iriure eum id, pri ei consul necessitatibus. Est te iusto epicuri. Vis no graece putent mentitum, rebum facete offendit nec in. In duis vivendo sed, vel id enim voluptatibus. Velit sanctus ne mel, quem sumo suavitate mel cu, mea ea nullam feugiat.
Tincidunt suscipiantur no pro. Vel ut novum mucius molestie, ut tale ipsum intellegebat mei, mazim accumsan voluptaria ea nam. Posidonium theophrastus ut sea, stet viris hendrerit pro ex, sonet mentitum ne quo. Vim duis feugiat ex, nec eu probo doming persecuti. Velit zril nam in, est commodo splendide id. Et aperiri fuisset iracundia usu. Eu nec iusto audire repudiare.</p>
<section>
<a style="margin: 500px 0px; color: initial;" name="section4">
<b style="font-size: 2em;">Section 4 <i>(this is an anchor tag, not a section)</i></b>
</a>
<p>
Lorem ipsum dolor sit amet, et vis laudem utroque, iusto forensibus neglegentur eu duo. Eu pro fuisset salutandi philosophia, discere persecuti qui te. Eos ad quodsi dissentias, ei odio viris signiferumque mei. Putent iuvaret perpetua nec eu. Has no ornatus vivendum. Adhuc nonumes ex vim, in suas rebum graecis mei, usu ad causae recusabo. Idque vituperata vel ea.
Veri verterem pro ex. Ad error omnes est, id sit lorem legendos. Eos vidit ullum ne, tale tantas omittam est ut. Nobis maiorum efficiendi eu mei. Eos et debet placerat signiferumque. Per eu propriae electram.
Impetus percipit menandri te ius, mea ne stet posse fabellas. Aliquid corrumpit vel no, mei in diam praesent contentiones. Qui veniam suscipit probatus ex. No autem homero perfecto quo, eos choro facilis ut. Te quo cibo interesset. Vel verear praesent in, menandri deserunt ad his.
Labore admodum consetetur has et. Possit facilisi eu sed, lorem iriure eum id, pri ei consul necessitatibus. Est te iusto epicuri. Vis no graece putent mentitum, rebum facete offendit nec in. In duis vivendo sed, vel id enim voluptatibus. Velit sanctus ne mel, quem sumo suavitate mel cu, mea ea nullam feugiat.
Tincidunt suscipiantur no pro. Vel ut novum mucius molestie, ut tale ipsum intellegebat mei, mazim accumsan voluptaria ea nam. Posidonium theophrastus ut sea, stet viris hendrerit pro ex, sonet mentitum ne quo. Vim duis feugiat ex, nec eu probo doming persecuti. Velit zril nam in, est commodo splendide id. Et aperiri fuisset iracundia usu. Eu nec iusto audire repudiare.</p>

There is a css way of doing this using scroll-behavior. Add the following property.
scroll-behavior: smooth;
And that is it. No JS required.
a {
display: inline-block;
width: 50px;
text-decoration: none;
}
nav, scroll-container {
display: block;
margin: 0 auto;
text-align: center;
}
nav {
width: 339px;
padding: 5px;
border: 1px solid black;
}
scroll-container {
display: block;
width: 350px;
height: 200px;
overflow-y: scroll;
scroll-behavior: smooth;
}
scroll-page {
display: flex;
align-items: center;
justify-content: center;
height: 100%;
font-size: 5em;
}
<nav>
1
2
3
</nav>
<scroll-container>
<scroll-page id="page-1">1</scroll-page>
<scroll-page id="page-2">2</scroll-page>
<scroll-page id="page-3">3</scroll-page>
</scroll-container>
PS: please check the browser compatibility.

The answer given works but disables outgoing links. Below a version with an added bonus ease out (swing) and respects outgoing links.
$(document).ready(function () {
$('a[href^="#"]').on('click', function (e) {
e.preventDefault();
var target = this.hash;
var $target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top
}, 900, 'swing', function () {
window.location.hash = target;
});
});
});

HTML
<a href="#target" class="smooth-scroll">
Link
</a>
<div id="target"></div>
or With absolute Full URL
<a href="https://somewebsite.com/#target" class="smooth-scroll">
Link
</a>
<div id="target"></div>
jQuery
$j(function() {
$j('a.smooth-scroll').click(function() {
if (
window.location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
&& window.location.hostname == this.hostname
) {
var target = $j(this.hash);
target = target.length ? target : $j('[name=' + this.hash.slice(1) + ']');
if (target.length) {
$j('html,body').animate({
scrollTop: target.offset().top - 70
}, 1000);
return false;
}
}
});
});

Modern browsers are a little faster these days. A setInterval might work. This function work well in Chrome and Firefox these days.(A little slow in safari, didn't bother with IE)
function smoothScroll(event) {
if (event.target.hash !== '') { //Check if tag is an anchor
event.preventDefault()
const hash = event.target.hash.replace("#", "")
const link = document.getElementsByName(hash)
//Find the where you want to scroll
const position = link[0].getBoundingClientRect().y
let top = 0
let smooth = setInterval(() => {
let leftover = position - top
if (top === position) {
clearInterval(smooth)
}
else if(position > top && leftover < 10) {
top += leftover
window.scrollTo(0, top)
}
else if(position > (top - 10)) {
top += 10
window.scrollTo(0, top)
}
}, 6)//6 milliseconds is the faster chrome runs setInterval
}
}

Adding this:
function () {
window.location.hash = href;
}
is somehow nullifying the vertical offset
top - 72
in Firefox and IE, ut not in Chrome. Basically, the page scrolls smoothly to the point at which it should stop based upon the offset, but then jumps down to where the page would go without the offset.
It does add the hash to the end of the url, but pressing back does not take you back to the top, it just removes the hash from the url and leaves the viewing window where it sits.
Here is the full js I am using:
var $root = $('html, body');
$('a').click(function() {
var href = $.attr(this, 'href');
$root.animate({
scrollTop: $(href).offset().top - 120
}, 500, function () {
window.location.hash = href;
});
return false;
});

This solution will also work for the following URLs, without breaking anchor links to different pages.
http://www.example.com/dir/index.html
http://www.example.com/dir/index.html#anchor
./index.html
./index.html#anchor
etc.
var $root = $('html, body');
$('a').on('click', function(event){
var hash = this.hash;
// Is the anchor on the same page?
if (hash && this.href.slice(0, -hash.length-1) == location.href.slice(0, -location.hash.length-1)) {
$root.animate({
scrollTop: $(hash).offset().top
}, 'normal', function() {
location.hash = hash;
});
return false;
}
});
I haven't tested this in all browsers, yet.

This will make it easy to allow jQuery to discern your target hash and know when and where to stop.
$('a[href*="#"]').click(function(e) {
e.preventDefault();
var target = this.hash;
$target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top
}, 900, 'swing', function () {
window.location.hash = target;
});
});

$("a").on("click", function(event){
//check the value of this.hash
if(this.hash !== ""){
event.preventDefault();
$("html, body").animate({scrollTop:$(this.hash).offset().top}, 500);
//add hash to the current scroll position
window.location.hash = this.hash;
}
});

Tested and Verified Code
<script>
jQuery(document).ready(function(){
// Add smooth scrolling to all links
jQuery("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
jQuery('html, body').animate({
scrollTop: jQuery(hash).offset().top
}, 800, function(){
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
} // End if
});
});
</script>

I did this for both "/xxxxx#asdf" and "#asdf" href anchors
$("a[href*=#]").on('click', function(event){
var href = $(this).attr("href");
if ( /(#.*)/.test(href) ){
var hash = href.match(/(#.*)/)[0];
var path = href.match(/([^#]*)/)[0];
if (window.location.pathname == path || path.length == 0){
event.preventDefault();
$('html,body').animate({scrollTop:$(this.hash).offset().top}, 1000);
window.location.hash = hash;
}
}
});

Here is the solution I implemented for multiple links and anchors, for a smooth scroll:
http://www.adriantomic.se/development/jquery-localscroll-tutorial/
if you have your navigation links set up in a navigation div and declared with this structure:
<a href = "#destinationA">
and your corresponding anchor tag destinations as so:
<a id = "destinationA">
Then just load this into the head of the document:
<!-- Load jQuery -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<!-- Load ScrollTo -->
<script src="http://flesler-plugins.googlecode.com/files/jquery.scrollTo-1.4.2-min.js"></script>
<!-- Load LocalScroll -->
<script src="http://flesler-plugins.googlecode.com/files/jquery.localscroll-1.2.7-min.js"></script>
<script type = "text/javascript">
$(document).ready(function()
{
// Scroll the whole document
$('#menuBox').localScroll({
target:'#content'
});
});
</script>
Thanks to #Adriantomic

If you have a simple button on the page to scroll down to a div and want the back button to work by jumping to top, just add this code:
$(window).on('hashchange', function(event) {
if (event.target.location.hash=="") {
window.scrollTo(0,0);
}
});
This could be extended to jump to different divs too, by reading the hash value, and scrolling like Joseph Silbers answer.

Never forget that offset() function is giving your element's position to document. So when you need scroll your element relative to its parent you should use this;
$('.a-parent-div').find('a').click(function(event){
event.preventDefault();
$('.scroll-div').animate({
scrollTop: $( $.attr(this, 'href') ).position().top + $('.scroll-div').scrollTop()
}, 500);
});
The key point is getting scrollTop of scroll-div and add it to scrollTop. If you won't do that position() function always gives you different position values.

thanks for sharing, Joseph Silber. Here your 2018 solution as ES6 with a minor change to keep the standard behavior (scroll to top):
document.querySelectorAll("a[href^=\"#\"]").forEach((anchor) => {
anchor.addEventListener("click", function (ev) {
ev.preventDefault();
const targetElement = document.querySelector(this.getAttribute("href"));
targetElement.scrollIntoView({
block: "start",
alignToTop: true,
behavior: "smooth"
});
});
});

Requires jquery and animates to anchor tag with the specified name instead of id, while adding the hash to browser url. Also fixes an error in most answers with jquery where the # sign is not prefixed with an escaping backslash. The back button, unfortunately, does not navigate back properly to previous hash links...
$('a[href*=\\#]').click(function (event)
{
let hashValue = $(this).attr('href');
let name = hashValue.substring(1);
let target = $('[name="' + name + '"]');
$('html, body').animate({ scrollTop: target.offset().top }, 500);
event.preventDefault();
history.pushState(null, null, hashValue);
});

Well, the solution depends on the type of problem, I use the javascript animate method for the button click. and I use codes from bellow links for the navbar
https://css-tricks.com/snippets/jquery/smooth-scrolling/
$(document).ready(function () {
$(".js--scroll-to-plans").click(function () {
$("body,html").animate(
{
scrollTop: $(".js--section-plans").offset().top,
},
1000
);
return false;
});
$(".js--scroll-to-start").click(function () {
$("body,html").animate(
{
scrollTop: $(".js--section-features").offset().top,
},
1000
);
return false;
});
$('a[href*="#"]')
// Remove links that don't actually link to anything
.not('[href="#"]')
.not('[href="#0"]')
.click(function(event) {
// On-page links
if (
location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
&&
location.hostname == this.hostname
) {
// Figure out element to scroll to
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
// Does a scroll target exist?
if (target.length) {
// Only prevent default if animation is actually gonna happen
event.preventDefault();
$('html, body').animate({
scrollTop: target.offset().top
}, 1000, function() {
// Callback after animation
// Must change focus!
var $target = $(target);
$target.focus();
if ($target.is(":focus")) { // Checking if the target was focused
return false;
} else {
$target.attr('tabindex','-1'); // Adding tabindex for elements not focusable
$target.focus(); // Set focus again
};
});
}
}
});
});

For users that are looking for a ReactJS (TypeScript) approach.
function Hero() {
const scrollToView = (e: any) => {
e.preventDefault();
// Scroll to a certain element
document.getElementById("about-section")?.scrollIntoView({
behavior: "smooth",
});
};
return (
<section id="hero">
<button
onClick={scrollToView}
>
Learn More
</button>
</section>
);
}
export default Hero;
And for the about-section component
const AboutSection = () => {
return (
<section id="about-section" >
<h1>About Section</h1>
</section>
);
};
export default AboutSection;

Related

changing the brightness of a web page using the slider

have a task in front of me - when changing the slider parameters to change the brightness of the entire page, I tried the option with a full-screen div, but it blocked access to the rest of the elements, I also tried to set the filter parameter for the body, but in this case the page construction went wrong
All you need to do is either use a filter: brightness(..) on <body>, make clever use of your website colors using hsl(..) colors and change their lightness value or a mix of both methods.
All can easily be done with a range slider modifying a single --brightness custom variable with one line of Javascript. Just en/disable the various options as mentioned in the CSS.
Just as a reminder: without a proper minimal reproducible example no one on SO will be able to help you with your specific issue...
I created a small demo showcasing the above:
/*
Custom variable to hold overall brightness percentage
modified with the range slider min [0.25] max [1.75]
default value [1].
Modified with slider "oninput" JS...
*/
html { --brightness: 1 }
.webpage {
margin-top: 3rem;
/* Default color setting */
background-color: hsl(0,0%, 41.2%); color: hsl(0,0%, 100%);
/* Override by changing (L)ightness parameter of HSL color */
background-color: hsl(0,0%, calc(var(--brightness) * 41.2%)); color: hsl(0,0%, calc(var(--brightness) * 100%));
/* disable when using filter */
/* Modify overall brightness */
/* filter: brightness(var(--brightness)); /* enable to see difference with HSL */
/* Modify overall brightness and invert B/W */
/* filter: brightness(var(--brightness)) invert(var(--brightness)); /* enable to see difference with HSL */
}
/* Extras, just to make the demo look good */
/********************************/
/* some convenient global rules */
/********************************/
*, ::before, ::after { box-sizing: border-box }
html, body { width: 100%; max-width: 100% }
html { scroll-behavior: smooth }
body { min-height: 100vh; margin: 0; line-height: 1.5 }
/************************************************/
/* element responsive behavior [STABLE] */
/************************************************/
/* https://codepen.io/renevanderlende/pen/YzEaKvO?editors=1100 */
/* responsive base font size using y = mx + b 'y-intercept form' => y = 0.00625x + 12 */
html { font-size: calc(0.625vmin + 0.75rem) } /* (320,14)(1280,20) */
body { font-size: 1rem; line-height: 1.5 }
/* Generic page spacers, root font size independent, also y = mx + bs
T/B: (360,0)(2160, 90) => y = 0.05x - 18 <= base 90, 72 at 1920x1080
L/R: (640,0)(1920,448) => y = 0.35x - 224 <= base 160, 360x640 full screen
*/
:root { --min-pad: 1rem }
[padded] { padding: max(var(--min-pad),calc(5vmin - 18px))
max(var(--min-pad),calc(35vw - 224px)) }
[padded="1"] { padding: var(--min-pad) } /* minimal padding */
[padded="0"] { padding: 0 } /* no padding */
label {
position: fixed; top: 0; width: 100%;
display: inline-flex; flex-direction: column;
background-color: white;
cursor: pointer;
}
<label>Brightness <input type="range" min="0.25" max="1.75" value="1" step="0.01"
oninput="javascript:document.documentElement.style.setProperty('--brightness', this.value)"> </label>
<div padded class="webpage">
<h2>Lorem Ipsum dolor...</h2>
<p>Lorem ipsum dolor sit amet, mel omnium vulputate percipitur ex. Ex vel quas inani appellantur. Iusto dolore cetero duo ad. Per facer mediocrem eu. An legimus voluptatibus eam, cetero aperiri consectetuer sit id, hinc sale evertitur cum ei.
</p>
<p>
Erant maiorum iracundia ius ne. Veri summo clita in usu, possim apeirian interesset usu no. Malorum repudiandae cu eum, ad vel putant torquatos. Idque feugait aliquando his eu, sed te sanctus omittam placerat. Ex eum ridens euismod facilisis, sea id lorem reformidans complectitur.
</p>
<p>
Qui purto elitr at, at corrumpit signiferumque mea. Vix quidam consulatu ei, no esse vocibus convenire usu, est te erroribus imperdiet. Soleat molestiae deseruisse ei sea, ea sale mollis nam. Ut eam eius vidit consulatu.
</p>
<p>
Amet justo ex mel. Utroque accusata cu nam. Et vel mucius audiam rationibus, mea regione alterum ne. Perpetua persequeris te eos, no sale mnesarchum quo. Atomorum reformidans ea per, ne timeam tractatos philosophia usu.
</p>
<p>
Id vix atomorum scribentur. Sit habeo ancillae facilisi in. Purto tacimates no mei, in duo nemore senserit, inani debet ut mea. Eu homero timeam adversarium vis, vix molestie luptatum atomorum ei. Ut eos sumo atqui, sumo ponderum iudicabit vix ne, ea errem maiorum postulant sea.
</p>
<p>
Et nam putant ancillae, et vel luptatum vivendum efficiendi, eos diam nulla legendos an. Putent fastidii mediocritatem sit in. Id per odio delenit complectitur. Altera mentitum efficiendi ex usu, an veri tation partiendo quo. In nominavi recteque adversarium mel, duo suas populo eu.
</p>
<p>
Et integre facilisi sea, et agam utinam nam. Facilis laboramus democritum sit at, eos sint probatus iracundia an, duo ei eirmod malorum. Pro quem nihil aliquip at. Eum dico debet graece ut, has tamquam intellegat an.
</p>
<p>
Sea no magna dolores corrumpit. Nam nulla hendrerit te, vivendum dissentiet eu vix, at quas zril putent vim. Eu pro maiestatis incorrupte, has magna posse ei, pri cetero quaerendum ut. Autem justo atqui usu id, sumo ipsum fierent pro ea. Oporteat tacimates suavitate per ei, molestie delicata at pro, erant prompta quo no.
</p>
<p>
Id qui elit partiendo iracundia, ei eos nostrud graecis. No postulant ullamcorper signiferumque qui, eu pri augue vidisse eligendi, corpora iudicabit et eos. Ea purto impetus per, porro partiendo efficiendi ex mel. Cum vero eius epicuri eu. An virtute albucius nec, hinc ceteros referrentur cu mei, audiam admodum ad nam.
</p>
<p>
Mel albucius qualisque ut, mutat simul omnesque at vim, te eam minim bonorum. Iisque insolens atomorum nam et. No nihil epicuri efficiantur pro. No mel vide argumentum, nonumes interesset nec ex. Duis commodo placerat pro cu, mei laudem aliquip numquam ut, case latine salutatus eum ne. Ad tollit convenire mei, nam te amet eruditi conclusionemque.
</p>
</div>

How do I disable mousewheel scroll

I tried this, it didn't work
$('body').bind("mousewheel", function() {
return false;
});
then I tried this
$('body').hover(function (){
$('body').css('overflow','hidden');
},
function (){
$('body').css('overflow','auto');
})
It sometimes works, but sometimes didn't work.
Is there any idea to disable the mouse wheel?
Note that in current versions of Chrome, scroll and wheel handlers are treated as passive by default and so can't be cancelled. See feature info.
I'm not sure if there's a way to specify an active handler using jQuery's on method, but you can do this fairly easy with the built-in addEventListener. Also, in this case return false won't work, you'll need to call preventDefault().
document.body.addEventListener('wheel', function(e){ e.preventDefault(); }, { passive: false });
p { width: 320px; }
<p>Lorem ipsum dolor sit amet, audire facilis no pri, ea eam duis laboramus, at pro atqui tollit meliore. Vis ut malorum vocibus percipit, nisl atqui ea sea. Illud errem te vix, ex facer omittam his. Ne sit consul suscipit. Eu usu percipit efficiendi dissentiet.</p>
<p>Te ius dictas oporteat facilisi. Dicta diceret debitis et vim. Paulo insolens comprehensam est cu, dolor assueverit eu mei. Pro an facilisis rationibus. Summo molestie mei cu. His nobis erroribus in, iuvaret repudiare delicatissimi mea ut, nec at elit nostro.</p>
<p>Ad augue invenire efficiendi qui, facilisi mediocritatem ei duo. Ceteros mnesarchum et has, at ius choro dolor verear. Purto sententiae interesset et vim, quis nisl facer vix ei. Est agam ocurreret assentior id, et partem fabellas vim.</p>
I've tested solution in Chrome 73 and Firefox 66. To make sure this works in all browsers, be sure to read MDN and quirksmode.

Why does the accordion open upwards for mobile?

The accordion sometimes open upwards instead of downwards and the issue appears to be caused by the "flex-direction". This is a problem because the user has to scroll up to the see beginning part of the ".content" div.
The accordion is in the right container and has been set to appear above the left container with "flex-direction".
How do I get the accordion to always open downwards with "flex-direction"?
var acc = document.getElementsByClassName("label");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].onclick = function(){
this.classList.toggle("active");
this.nextElementSibling.classList.toggle("show");
}
}
.stuff {
background:#ebeef2;
padding:1em;
box-sizing:border-box;
}
.container {
display:flex;
flex-direction:column;
}
.left,
.right {
width:100%;
}
.left {
order:2;
background:blue;
padding:1em;
box-sizing:border-box;
}
.right {
order:1;
background:green;
padding:1em;
box-sizing:border-box;
}
.label {
font-size:2em;
font-weight:bold;
cursor: pointer;
position:relative;
-webkit-transition: all 300ms ease;
-moz-transition: all 300ms ease;
-ms-transition: all 300ms ease;
-o-transition: all 300ms ease;
transition: all 300ms ease;
}
.content {
max-height: 0;
opacity: 0;
overflow: hidden;
-webkit-transition: all 300ms ease;
-moz-transition: all 300ms ease;
-ms-transition: all 300ms ease;
-o-transition: all 300ms ease;
transition: all 300ms ease;
padding:1em;
box-sizing:border-box;
}
.content.show {
opacity: 1;
max-height: 100%;
}
.label:after {
content: '+';
font-size: 32px;
right: 10px;
top: 0;
position: absolute;
font-weight: 100;
}
.label.active:after {
content: '-';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="stuff">In ridens invenire sit. Vel ponderum vulputate ex, mel no erant dissentias interpretaris. Amet dicat possit vel eu, habeo vivendum senserit duo no. Duo ne alii facete inciderint.Cum aliquam persecuti cu, in lorem dicit sonet vix, est soluta noster ex. An nam novum verear antiopam, nominati moderatius vel at. Pro quis impetus consequuntur in, autem augue deleniti eos cu, sea cu quis integre pertinax. Ut vitae mucius vix, ei eos meis ludus. Reque facilisis ex mel, sea in tota lobortis disputationi. Sed quas clita saepe te, te mollis vocent sed. In ridens invenire sit. Vel ponderum vulputate ex, mel no erant dissentias interpretaris. Amet dicat possit vel eu, habeo vivendum senserit duo no. Duo ne alii facete inciderint.Cum aliquam persecuti cu, in lorem dicit sonet vix, est soluta noster ex. An nam novum verear antiopam, nominati moderatius vel at. Pro quis impetus consequuntur in, autem augue deleniti eos cu, sea cu quis integre pertinax. Ut vitae mucius vix, ei eos meis ludus. Reque facilisis ex mel, sea in tota lobortis disputationi. Sed quas clita saepe te, te mollis vocent sed. In ridens invenire sit. Vel ponderum vulputate ex, mel no erant dissentias interpretaris. Amet dicat possit vel eu, habeo vivendum senserit duo no. Duo ne alii facete inciderint.Cum aliquam persecuti cu, in lorem dicit sonet vix, est soluta noster ex. An nam novum verear antiopam, nominati moderatius vel at. Pro quis impetus consequuntur in, autem augue deleniti eos cu, sea cu quis integre pertinax. Ut vitae mucius vix, ei eos meis ludus. Reque facilisis ex mel, sea in tota lobortis disputationi. Sed quas clita saepe te, te mollis vocent sed. In ridens invenire sit. Vel ponderum vulputate ex, mel no erant dissentias interpretaris. Amet dicat possit vel eu, habeo vivendum senserit duo no. Duo ne alii facete inciderint.Cum aliquam persecuti cu, in lorem dicit sonet vix, est soluta noster ex. An nam novum verear antiopam, nominati moderatius vel at. Pro quis impetus consequuntur in, autem augue deleniti eos cu, sea cu quis integre pertinax. Ut vitae mucius vix, ei eos meis ludus. Reque facilisis ex mel, sea in tota lobortis disputationi. Sed quas clita saepe te, te mollis vocent sed.</div>
<div class="container">
<div class="left">Left Side</div>
<div class="right">
<div class="label">Label 1</div>
<div class="content">Content 1</div>
<div class="label">Label 2</div>
<div class="content">Content 2</div>
<div class="label">Label 3</div>
<div class="content">Content 3</div>
<div class="label">Label 4</div>
<div class="content">Content 4</div>
</div>
</div>
<div class="stuff">In ridens invenire sit. Vel ponderum vulputate ex, mel no erant dissentias interpretaris. Amet dicat possit vel eu, habeo vivendum senserit duo no. Duo ne alii facete inciderint.Cum aliquam persecuti cu, in lorem dicit sonet vix, est soluta noster ex. An nam novum verear antiopam, nominati moderatius vel at. Pro quis impetus consequuntur in, autem augue deleniti eos cu, sea cu quis integre pertinax. Ut vitae mucius vix, ei eos meis ludus. Reque facilisis ex mel, sea in tota lobortis disputationi. Sed quas clita saepe te, te mollis vocent sed. In ridens invenire sit. Vel ponderum vulputate ex, mel no erant dissentias interpretaris. Amet dicat possit vel eu, habeo vivendum senserit duo no. Duo ne alii facete inciderint.Cum aliquam persecuti cu, in lorem dicit sonet vix, est soluta noster ex. An nam novum verear antiopam, nominati moderatius vel at. Pro quis impetus consequuntur in, autem augue deleniti eos cu, sea cu quis integre pertinax. Ut vitae mucius vix, ei eos meis ludus. Reque facilisis ex mel, sea in tota lobortis disputationi. Sed quas clita saepe te, te mollis vocent sed. In ridens invenire sit. Vel ponderum vulputate ex, mel no erant dissentias interpretaris. Amet dicat possit vel eu, habeo vivendum senserit duo no. Duo ne alii facete inciderint.Cum aliquam persecuti cu, in lorem dicit sonet vix, est soluta noster ex. An nam novum verear antiopam, nominati moderatius vel at. Pro quis impetus consequuntur in, autem augue deleniti eos cu, sea cu quis integre pertinax. Ut vitae mucius vix, ei eos meis ludus. Reque facilisis ex mel, sea in tota lobortis disputationi. Sed quas clita saepe te, te mollis vocent sed. In ridens invenire sit. Vel ponderum vulputate ex, mel no erant dissentias interpretaris. Amet dicat possit vel eu, habeo vivendum senserit duo no. Duo ne alii facete inciderint.Cum aliquam persecuti cu, in lorem dicit sonet vix, est soluta noster ex. An nam novum verear antiopam, nominati moderatius vel at. Pro quis impetus consequuntur in, autem augue deleniti eos cu, sea cu quis integre pertinax. Ut vitae mucius vix, ei eos meis ludus. Reque facilisis ex mel, sea in tota lobortis disputationi. Sed quas clita saepe te, te mollis vocent sed.</div>
Setting the max-height to 100% on open won't actually animate the height change. For that to work with CSS, you need to set a precise value in a fixed unit, like 200px. This might cause jumping on the screen. Since jquery is already included, you might be better with slideToggle()

Why does the accordion open upwards with "flex-direction:column"?

My layout consist of 2 columns, the left side has text and the right side has an accordion. The right side has been positioned with "flex-direction" to appear on top of the left side, but this causes the accordion within the right side to open upwards in stead of downwards.
How do I get the accordion in the right side to always open downwards when the parent div uses "flex-direction: column"?
var acc = document.getElementsByClassName("label");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].onclick = function() {
this.classList.toggle("active");
this.nextElementSibling.classList.toggle("show");
}
}
.stuff {
background: #ebeef2;
}
.container {
display: flex;
flex-direction: column;
}
.left,
.right {
width: 100%;
}
.left {
order: 2;
background: blue;
}
.right {
order: 1;
background: green;
}
.label {
font-size: 2em;
font-weight: bold;
cursor: pointer;
position: relative;
-webkit-transition: all 300ms ease;
-moz-transition: all 300ms ease;
-ms-transition: all 300ms ease;
-o-transition: all 300ms ease;
transition: all 300ms ease;
}
.content {
max-height: 0;
opacity: 0;
overflow: hidden;
-webkit-transition: all 300ms ease;
-moz-transition: all 300ms ease;
-ms-transition: all 300ms ease;
-o-transition: all 300ms ease;
transition: all 300ms ease;
padding: 1em;
box-sizing: border-box;
}
.content.show {
opacity: 1;
max-height: 100%;
}
.label:after {
content: '+';
font-size: 32px;
right: 10px;
top: 0;
position: absolute;
font-weight: 100;
}
.label.active:after {
content: '-';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="stuff">In ridens invenire sit. Vel ponderum vulputate ex, mel no erant dissentias interpretaris. Amet dicat possit vel eu, habeo vivendum senserit duo no. Duo ne alii facete inciderint.Cum aliquam persecuti cu, in lorem dicit sonet vix, est soluta noster ex.
An nam novum verear antiopam, nominati moderatius vel at. Pro quis impetus consequuntur in, autem augue deleniti eos cu, sea cu quis integre pertinax. Ut vitae mucius vix, ei eos meis ludus. Reque facilisis ex mel, sea in tota lobortis disputationi.
Sed quas clita saepe te, te mollis vocent sed. In ridens invenire sit. Vel ponderum vulputate ex, mel no erant dissentias interpretaris. Amet dicat possit vel eu, habeo vivendum senserit duo no. Duo ne alii facete inciderint.Cum aliquam persecuti cu,
in lorem dicit sonet vix, est soluta noster ex. An nam novum verear antiopam, nominati moderatius vel at. Pro quis impetus consequuntur in, autem augue deleniti eos cu, sea cu quis integre pertinax. Ut vitae mucius vix, ei eos meis ludus. Reque facilisis
ex mel, sea in tota lobortis disputationi. Sed quas clita saepe te, te mollis vocent sed. In ridens invenire sit. Vel ponderum vulputate ex, mel no erant dissentias interpretaris. Amet dicat possit vel eu, habeo vivendum senserit duo no. Duo ne alii
facete inciderint.Cum aliquam persecuti cu, in lorem dicit sonet vix, est soluta noster ex. An nam novum verear antiopam, nominati moderatius vel at. Pro quis impetus consequuntur in, autem augue deleniti eos cu, sea cu quis integre pertinax. Ut vitae
mucius vix, ei eos meis ludus. Reque facilisis ex mel, sea in tota lobortis disputationi. Sed quas clita saepe te, te mollis vocent sed. In ridens invenire sit. Vel ponderum vulputate ex, mel no erant dissentias interpretaris. Amet dicat possit vel
eu, habeo vivendum senserit duo no. Duo ne alii facete inciderint.Cum aliquam persecuti cu, in lorem dicit sonet vix, est soluta noster ex. An nam novum verear antiopam, nominati moderatius vel at. Pro quis impetus consequuntur in, autem augue deleniti
eos cu, sea cu quis integre pertinax. Ut vitae mucius vix, ei eos meis ludus. Reque facilisis ex mel, sea in tota lobortis disputationi. Sed quas clita saepe te, te mollis vocent sed.</div>
<div class="container">
<div class="left">Left Side</div>
<div class="right">
<div class="label">Label 1</div>
<div class="content">Content 1</div>
<div class="label">Label 2</div>
<div class="content">Content 2</div>
<div class="label">Label 3</div>
<div class="content">Content 3</div>
<div class="label">Label 4</div>
<div class="content">Content 4</div>
</div>
</div>
<div class="stuff">In ridens invenire sit. Vel ponderum vulputate ex, mel no erant dissentias interpretaris. Amet dicat possit vel eu, habeo vivendum senserit duo no. Duo ne alii facete inciderint.Cum aliquam persecuti cu, in lorem dicit sonet vix, est soluta noster ex.
An nam novum verear antiopam, nominati moderatius vel at. Pro quis impetus consequuntur in, autem augue deleniti eos cu, sea cu quis integre pertinax. Ut vitae mucius vix, ei eos meis ludus. Reque facilisis ex mel, sea in tota lobortis disputationi.
Sed quas clita saepe te, te mollis vocent sed. In ridens invenire sit. Vel ponderum vulputate ex, mel no erant dissentias interpretaris. Amet dicat possit vel eu, habeo vivendum senserit duo no. Duo ne alii facete inciderint.Cum aliquam persecuti cu,
in lorem dicit sonet vix, est soluta noster ex. An nam novum verear antiopam, nominati moderatius vel at. Pro quis impetus consequuntur in, autem augue deleniti eos cu, sea cu quis integre pertinax. Ut vitae mucius vix, ei eos meis ludus. Reque facilisis
ex mel, sea in tota lobortis disputationi. Sed quas clita saepe te, te mollis vocent sed. In ridens invenire sit. Vel ponderum vulputate ex, mel no erant dissentias interpretaris. Amet dicat possit vel eu, habeo vivendum senserit duo no. Duo ne alii
facete inciderint.Cum aliquam persecuti cu, in lorem dicit sonet vix, est soluta noster ex. An nam novum verear antiopam, nominati moderatius vel at. Pro quis impetus consequuntur in, autem augue deleniti eos cu, sea cu quis integre pertinax. Ut vitae
mucius vix, ei eos meis ludus. Reque facilisis ex mel, sea in tota lobortis disputationi. Sed quas clita saepe te, te mollis vocent sed. In ridens invenire sit. Vel ponderum vulputate ex, mel no erant dissentias interpretaris. Amet dicat possit vel
eu, habeo vivendum senserit duo no. Duo ne alii facete inciderint.Cum aliquam persecuti cu, in lorem dicit sonet vix, est soluta noster ex. An nam novum verear antiopam, nominati moderatius vel at. Pro quis impetus consequuntur in, autem augue deleniti
eos cu, sea cu quis integre pertinax. Ut vitae mucius vix, ei eos meis ludus. Reque facilisis ex mel, sea in tota lobortis disputationi. Sed quas clita saepe te, te mollis vocent sed.</div>

How can I reset active touch-event-listeners inside YouTube embed <iframe>?

tl;dr:
YouTube embedded video <iframe> tags have touch-event-listeners. Active touch-event listeners cause scroll performance issues - AKA jank. I usually manage to fix active touch-event related jank issues by using touch-action: initial in CSS. This does not work for Youtube embedded video <iframe> elements.
Intro:
Kayce Basques - Google techie - writes:
When you scroll a page and there's such a delay that the page doesn't feel anchored to your finger, that's called scroll jank. Many times when you encounter scroll jank, the culprit is a touch event listener.
Touch event listeners are often useful for tracking user interactions
and creating custom scroll experiences, such as cancelling the scroll
altogether when interacting with an embedded Google Map.
Currently,
browsers can't know if a touch event listener is going to cancel the
scroll, so they always wait for the listener to finish before
scrolling the page.
I have found a way to sidestep this with CSS using touch-action
The touch-action CSS property specifies whether, and in what ways, a given region can be manipulated by the user via a touchscreen (for instance, by panning or zooming features built into the browser).
If I use touch-action: initial the problem disappears.
If you want to see what causes scroll jank and what does not, examine the screenshot below
Red buttons cause jank while green ones don't. The only differece between the two is that red buttons are set to touch-action: manipulation which makes red buttons actively "listen" and process input before scrolling can proceed
The issue
I embed videos from Youtube. The iframes contain touch event listeners that are active. The method I mentioned above does not work. I don't have access to Youtube code to edit the listeners and set them to passive.
I have tried to narrow down the issue. I have found that the element with the class .html5-video-player has the following CSS
.html5-video-player {
touch-action: manipulation;
}
According to the docs, manipulation can
[...] Enable panning and pinch zoom gestures, but disable additional
non-standard gestures such as double-tap to zoom. Disabling double-tap
to zoom removes the need for browsers to delay the generation of click
events when the user taps the screen. This is an alias for "pan-x
pan-y pinch-zoom" (which, for compatibility, is itself still valid).
and
[...] is also often used to completely disable the delay of click
events caused by support for the double-tap to zoom gesture.
All of which are things I don't need.
Logic says all I need to do is add this to my CSS
.html5-video-player {
touch-action: initial;
}
but that doesn't work, nor does this:
.html5-video-player {
touch-action: initial !important;
}
or this:
.html5-video-player {
touch-action: unset !important;
touch-action: initial !important;
}
or even this:
.html5-video-player {
touch-action: none !important;
}
Even if I try a different approach like:
*>iframe,
iframe>*,
*>.html5-video-player,
.html5-video-player>*,
.html5-video-player,
iframe>*>.html5-video-player,
iframe .html5-video-player {
/* <---- All of these don't work */
touch-action: initial /* and all other variations mentioned above */
}
It still does not work.
For a reference on what it actually looks like on screen examine the screenshot below
Code sandbox:
* {
max-width: 500px;
margin: 1em auto;
text-align: justify
}
button {
color: white !important;
background: green;
}
button:nth-child(odd) {
/* <---- these buttons have active touch event listners and hinder scrolling */
background: red;
touch-action: manipulation
}
*>iframe,
iframe>*,
*>.html5-video-player,
.html5-video-player>*,
.html5-video-player,
iframe .html5-video-player {
/* <---- All of these don't work */
touch-action: initial
}
<p>Lorem ipsum dolor sit amet, ea audiam feugiat voluptatibus mea, eum ex prima electram. Malis tamquam ad nam, ius ne laudem accusata dissentiet. Quidam vocent inciderint eu sea, mel eu consul constituto, vix congue quidam fierent id. Et justo tantas populo
his, laudem altera mei an. An dictas ancillae mediocrem ius. Exerci scaevola ei nam, ad vel prima mandamus. Pro eu eruditi probatus splendide, has ex nonumes minimum, sint blandit an sea. Etiam tincidunt his ad, ex assum fabellas deterruisset vix. Usu
ex diam molestiae similique, an viris aliquip tacimates eam. Cum vitae nonumes te, ne ius nostro omittam probatus, mea te meis commodo reprehendunt. Purto omittam probatus at eam. Eam fugit inermis ut, cu fastidii inimicus vituperatoribus usu. Libris
sapientem posidonium mea ut, an ipsum postulant referrentur mea. Et vim nihil ponderum disputationi, fuisset menandri percipitur sed te, labores mnesarchum appellantur has et.<button>Button</button> Brute tation sea te, quas temporibus vel an. Nam cu
legere malorum, sea ut<button>Button</button> tollit insolens reformidans. Ut mei vide mucius copiosae, eum laudem eligendi an. Invidunt deterruisset an his, ex duis apeirian vel. Cum ut quaeque sensibus expetenda. Nec cu audiam delicatissimi. Ius quod
vulputate constituam no, cu lobortis consectetuer duo. Tota simul populo et quo, ad per aliquip graecis consetetur, mei et adhuc laboramus. Aeque nostro vocent eu quo, ad alia virtute pro, eu sit graeci honestatis. Dolore volutpat efficiendi nam id,
in pro case choro. Cum in liber dissentiunt necessitatibus. Sit ut recusabo sadipscing disputando, congue salutatus scribentur duo ei. Vim eu natum integre feugait, at esse tincidunt usu. Nonumy accusata in cum. Augue voluptua antiopam in nec, ut aperiam
albucius detraxit usu. Mucius salutatus mei no, congue maiestatis pro cu. Agam tota volutpat usu ne, atqui scribentur dissentiet in usu. Vel justo option pertinax at, justo essent at sit. Mea te vivendo conceptam,<button>Button</button> eos sonet antiopam
concludaturque ea, eos ei falli oporteat deserunt. Ne vix libris scripta prompta, vis ex vitae impetus mandamus. Pri ne populo incorrupte percipitur, reque putent dignissim et vis. Saepe fuisset qui eu, in probo assueverit nam. An quo scriptorem appellantur
disputationi, usu dicta veritus in. Ne deterruisset voluptatibus qui, cu usu tamquam persecuti, pri detracto gloriatur definitiones id. Veniam inermis ut has. In timeam efficiendi efficiantur his, vix posse facilis ea, altera sententiae consectetuer
eu mea. Eu qui sonet nusquam molestie, ex dicant <button>Button</button>facete platonem mea, in facer alterum his. Cu eum appetere sadipscing. Alii eirmod invenire est ea. Te qui modo ponderum maluisset, saepe exerci accumsan est et. Unum quas velit
ei ius, sit ridens commune conceptam ei. Est purto putent accusamus in. In mel graeci labores, eos enim idque ex. Id tollit putent sed, laoreet accommodare consectetuer eu duo. Augue facilisi explicari no vis. Eu cum placerat gloriatur, vel virtute
vituperatoribus ex, ipsum ocurreret eu sed. At his aliquid adolescens, delectus deterruisset eu<button>Button</button> pro. His dicat dolores ex, vel id tempor referrentur, agam congue maiestatis nec id. Ei vix option menandri appellantur. Fabulas graecis
ponderum mea te. Ad solum maluisset assentior eam, qui libris indoctum scriptorem cu. At elit legere iisque sea, eius ponderum et nam. Has ne aliquid impedit corrumpit, an munere rationibus sea. Ut qui facilis vivendo consectetuer. Explicari neglegentur
comprehensam te pri. Sanctus iudicabit deterruisset ea his. Nam te affert nullam, ex diam contentiones vix. Mel cu nisl autem docendi. Cu possit tamquam aliquid eum, congue iudico ut pro, lobortis praesent at quo. Vim cu tibique adipiscing. His nobis
vocent tritani et. Mei ne deserunt constituam, usu prima putant et. In has duis audiam delectus, id nam tota delectus, no sanctus facilisi accusata sed. Audire deseruisse qui ei, no mel soleat doming, an pri agam posse eleifend. Duo lucilius elaboraret
et. Eu illud ludus aperiri duo, cu malis dolorem eos. Reque aperiri similique vim ut, eu vel hinc possit. No nusquam nominavi elaboraret sea, at solum ignota his. At quando everti definitionem pri. Eu eum meis consulatu, nec audiam vivendo ne, eruditi
accusamus persequeris cum no. Nam ne purto legimus. Qui saepe utroque meliore in. Dicunt nonumes referrentur per id. Ne mel pertinacia constituto appellantur. Eos cu alii habeo iudicabit. Nec et verterem abhorreant quaerendum, qui an nobis noluisse
consectetuer, no vero utinam facete has. Eu semper impetus intellegebat vis, ad mea scripta percipit, et cibo zril clita mel. Quo elitr partiendo comprehensam no. Mundi quaerendum at usu. Vel et iisque comprehensam vituperatoribus. Has appetere moderatius
et, agam decore conceptam no pro, vide aliquam salutandi cum te. Quo probo deleniti imperdiet ne. Facer dignissim ad sed, possit lucilius moderatius ne eum, eius reque eam ex. Assum fierent pro no. Eu ignota commodo facilis eum, per ex mutat mandamus
mediocrem. Ei his tamquam perpetua. Ei epicurei erroribus disputationi usu. Eos delenit aliquando tincidunt eu. Ad option utamur nam, quo eu munere altera delenit, causae ornatus molestie no vix. Pro ne antiopam consulatu. Ea mei accusam mentitum appetere,
mea prima tincidunt assueverit at. Ius appetere accusamus ex, pri an justo sonet. Ne omnis iisque per. Dicam menandri ea mel. Audiam assentior no mel, ea dicam vituperata pri, at eum timeam offendit vivendum. In eum voluptatibus vituperatoribus, et
mei meis inani putent. Sit eu aliquid tractatos definiebas. Populo omnesque necessitatibus eum no, dicant graece dolores vix ne. Nec ei homero recusabo complectitur, graecis urbanitas in duo. Prima complectitur id vim, no quas causae expetendis duo.
Volumus recusabo adolescens ut duo. No eos erat electram instructior, adhuc nemore conceptam et duo</p>
<iframe width="560" height="315" src="https://www.youtube.com/embed/6h4_-F6jnyk?rel=0&controls=0&showinfo=0" frameborder="0" allowfullscreen></iframe>
<p>Lorem ipsum dolor sit amet, ea audiam feugiat voluptatibus mea, eum ex prima electram. Malis tamquam ad nam, ius ne laudem accusata dissentiet. Quidam vocent inciderint eu sea, mel eu consul constituto, vix congue quidam fierent id. Et justo tantas populo
his, laudem altera mei an. An dictas ancillae mediocrem ius. Exerci scaevola ei nam, ad vel prima mandamus. Pro eu eruditi probatus splendide, has ex nonumes minimum, sint<button>Button</button> blandit an sea. Etiam tincidunt his ad, ex assum fabellas
deterruisset vix. Usu ex diam molestiae similique, an viris aliquip tacimates eam. Cum vitae nonumes te, ne ius nostro omittam probatus, mea te meis commodo reprehendunt. Purto omittam probatus at eam. Eam fugit inermis ut, cu fastidii inimicus vituperatoribus
usu. Libris sapientem posidonium mea ut, an ipsum postulant referrentur mea. Et vim nihil ponderum disputationi, fuisset menandri percipitur sed te, labores mnesarchum appellantur has et. Brute tation sea te, quas temporibus vel an. Nam cu legere malorum,
sea ut tollit insolens reformidans. Ut mei vide<button>Button</button> mucius copiosae, eum laudem eligendi an. Invidunt deterruisset an his, ex duis apeirian vel. Cum ut quaeque sensibus expetenda. Nec cu audiam delicatissimi. Ius quod vulputate constituam
no, cu lobortis consectetuer duo. Tota simul populo et quo, ad per aliquip graecis consetetur, mei et adhuc laboramus. Aeque nostro vocent eu quo, ad alia virtute pro, eu sit graeci honestatis. Dolore volutpat efficiendi nam id, in pro case choro. Cum
in liber dissentiunt necessitatibus. Sit ut recusabo sadipscing disputando, congue salutatus scribentur duo ei. Vim eu natum integre feugait, at esse tincidunt usu. Nonumy accusata in cum. Augue voluptua antiopam in nec, ut aperiam albucius detraxit
usu. Mucius salutatus mei no, congue maiestatis pro cu. Agam tota volutpat usu ne, atqui scribentur dissentiet in usu. Vel justo option pertinax at, justo essent at sit. Mea te vivendo conceptam, eos sonet antiopam concludaturque ea, eos ei falli oporteat
deserunt. Ne vix libris scripta prompta, vis ex vitae impetus mandamus. Pri ne populo incorrupte percipitur, reque putent dignissim et vis. Saepe fuisset qui eu, in probo assueverit nam. An quo scriptorem appellantur disputationi, usu dicta veritus
in. Ne deterruisset voluptatibus qui, cu usu tamquam persecuti, pri detracto gloriatur definitiones id. Veniam inermis ut has. In timeam efficiendi efficiantur his, vix posse facilis ea, altera sententiae consectetuer eu mea. Eu qui sonet nusquam molestie,
ex dicant facete platonem mea, in facer alterum his. Cu eum appetere sadipscing. Alii eirmod invenire est ea. Te qui modo ponderum maluisset, saepe exerci accumsan est et. Unum quas velit ei ius, sit ridens commune conceptam ei. Est purto putent accusamus
in. In mel graeci labores, eos enim idque ex. Id tollit putent sed, laoreet accommodare consectetuer eu duo. Augue facilisi explicari no vis. Eu cum placerat gloriatur, vel virtute vituperatoribus ex, ipsum ocurreret eu sed. At his aliquid adolescens,
delectus deterruisset eu pro. His dicat dolores ex, vel id tempor referrentur, agam congue maiestatis nec id. Ei vix option menandri appellantur. Fabulas graecis ponderum mea te. Ad solum maluisset assentior eam, qui libris indoctum scriptorem cu. At
elit legere iisque sea, eius ponderum et nam. Has ne aliquid impedit corrumpit, an munere rationibus sea. Ut qui facilis vivendo consectetuer. Explicari neglegentur comprehensam te pri. Sanctus iudicabit deterruisset ea his. Nam te affert nullam, ex
diam contentiones vix. Mel cu nisl autem docendi. Cu possit tamquam aliquid eum, congue iudico ut pro, lobortis praesent at quo. Vim cu tibique adipiscing. His nobis vocent tritani et. Mei ne deserunt constituam, usu prima putant et. In has duis audiam
delectus, id nam tota delectus, no sanctus facilisi accusata sed. Audire deseruisse qui ei, no mel soleat doming, an pri agam posse eleifend. Duo lucilius elaboraret et. Eu illud ludus aperiri duo, cu malis dolorem eos. Reque aperiri similique vim ut,
eu vel hinc possit. No nusquam nominavi elaboraret sea, at solum ignota his. At quando everti definitionem pri. Eu eum meis consulatu, nec audiam vivendo ne, eruditi accusamus persequeris cum no. Nam ne purto legimus. Qui saepe utroque meliore in. Dicunt
nonumes referrentur per id. Ne mel pertinacia constituto appellantur. Eos cu alii habeo iudicabit. Nec et verterem abhorreant quaerendum, qui an nobis noluisse consectetuer, no vero utinam facete has. Eu semper impetus intellegebat vis, ad mea scripta
percipit, et cibo<button>Button</button> zril clita mel. Quo elitr<button>Button</button> partiendo comprehensam no. Mundi quaerendum at usu. Vel et iisque comprehensam vituperatoribus. Has appetere moderatius et, agam decore conceptam no pro, vide
aliquam salutandi cum te. Quo probo deleniti imperdiet ne. Facer dignissim ad sed, possit lucilius moderatius ne eum, eius reque eam ex. Assum fierent pro no. Eu ignota commodo facilis eum, per ex mutat mandamus mediocrem. Ei his tamquam perpetua. Ei
epicurei erroribus disputationi usu. Eos delenit aliquando tincidunt eu. Ad option utamur nam, quo eu munere altera delenit, causae ornatus molestie no vix. Pro ne antiopam consulatu. Ea mei accusam mentitum appetere, mea prima tincidunt assueverit
at. Ius appetere accusamus ex, pri an justo sonet. Ne omnis iisque per. Dicam menandri ea mel.<button>Button</button> Audiam assentior no mel, ea dicam vituperata pri, at eum timeam offendit vivendum. In eum voluptatibus vituperatoribus, et mei meis
inani putent. Sit eu aliquid tractatos definiebas. Populo omnesque necessitatibus eum no, dicant graece dolores vix ne. Nec ei homero recusabo complectitur, graecis urbanitas in duo. Prima complectitur id vim, no quas causae expetendis duo. Volumus
recusabo adolescens ut duo. No eos erat electram instructior, adhuc nemore conceptam et duo</p>
Question:
How can I turn off / disable / reset the touch event listener inside a Youtube embed <iframe>?
You can't apply a CSS style to an <iframe> - it's a new document with a new CSS cascade.
Instead you'll need some JS to apply the style property to the new document, and you'll need a CORS header set or host the <iframe> on your own domain.
That done you can manipulate the <iframe> content to include your styles. There are better answers already on here to help with that.
However, even if you can that may not be enough, as YouTube are switching to apply Shadow DOM (they already do if you opted in) in which case the video player itself gets a shadow style tree that you can't access from the <iframe>.
In your snippet you're embedding an <iframe> directly. Instead use the YouTube API to create the player. This exposes player.removeEventListener(), which can remove the janky events and player.getIframe() that gives you access to the frame's DOM directly.
You can also access the player in the creation event:
// Loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// Once the script has loaded add the player
function onYouTubeIframeAPIReady() {
var player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'ylLzyHk54Z0',
events: {
'onReady': onPlayerReady
}
});
}
// Once the player is ready set its style
function onPlayerReady(event) {
event.target.style.touchAction = 'initial';
}
<div id="player"></div>
Though that snippet has loads of errors due to the preview using a sandbox <iframe> of its own.

Categories

Resources