Material Design Lite and jQuery, smooth scroll does not work

I cannot use the .animate jQuery method with Google Material Design Lite (MDL). I used MDL to create a navigation bar, but smooth scrolling did not work.

Simple jQuery code:

$(function(){ $('a.smooth').click(function(){ console.log("SMOOTH BEGIN"); var speed = 1000; var href= $(this).attr("href"); var target = $(href == "#" || href == "" ? 'html' : href); var position = target.offset().top; $("html, body").animate({scrollTop:position}, speed, "swing"); console.log("SMOOTH END"); }); }); 

And a simple html code:

 <!-- Navigation (this is included header) --> <nav class="mdl-navigation"> <a class="mdl-navigation__link" href="">Home</a> <a class="mdl-navigation__link smooth" href="#product">Product</a> </nav> <!--Main contents --> <main class="mdl-layout__content"> <div id="product"><!—-Contents-—></div> </main> 

This code showed me the magazine "SMOOTH BEGIN" and "SMOOTH END". However, this link worked like a regular link, not a smooth one. How can I get jQuery to work with MDL? Some conflicts may occur, but the console does not show anything.

+4
source share
2 answers

The reason you don't see anything is because you are scrolling the node body. MDL handles overflow inside mdl-layout__content , this is an element that you should scroll through.

So this is -

 $("html, body").animate({scrollTop:position}, speed, "swing"); 

Now it becomes -

 $(".mdl-layout__content").animate({scrollTop:position}, speed, "swing"); 

Here's a codepen example - http://codepen.io/mdlhut/pen/BNeoVa

+14
source
Mitsuhiko Shimomura helped me in another matter. Instead var position = target.offset().top; I used var position = target.get( 0 ).offsetTop - 130; if the scrolling hadn’t returned and lost its position, it didn’t look very good. I had to add - 130 in .offsetTop , because smooth scrolling passed by my target id in html. Thank you for your help! See My application for where I used this smoothing feature.

And don't forget to add a smooth class to the anchors in html like this

 <a class="smooth" href="#scrollToId">Target</a> <div id="scrollToId">Target</div> $(function(){ $('a.smooth').click(function(){ console.log("SMOOTH BEGIN"); var speed = 1000; var href= $(this).attr("href"); var target = $(href == "#" || href == "" ? 'html' : href); var position = target.get( 0 ).offsetTop - 130; $(".mdl-layout__content").animate({scrollTop:position}, speed, "swing"); console.log("SMOOTH END"); }); }); 
0
source

All Articles