Mitsuhiko Shimomura Mitsuhiko Shimomura - 6 months ago 56
Javascript Question

Material Design Lite and jQuery, something is wrong with smooth scroll

Yesterday, I asked similar question, here.

And smooth scroll has worked.

However, something is wrong with smooth scroll when I used it.

Code is here ( this repository include 1 html file and 1 image file):

https://github.com/MitsuhikoShimomura/mdl-error

Some important parts of the code.

Smooth Scroll:

<script>
$(function(){
$("a.smooth").click(function(e){
e.preventDefault();
var speed = 500;
var href= $(this).attr("href");
var target = $(href == "#" || href == "" ? 'html' : href);
var nav_height = $(".mdl-layout__header-row").height();
var position = target.offset().top - nav_height;
$(".mdl-layout__content").animate({scrollTop:position}, speed, "swing");
return false;
});
});
</script>


Body contents:

<div class="layout-transparent mdl-layout mdl-js-layout">
<header class="mdl-layout__header mdl-layout__header--transparent">
<div class="mdl-layout__header-row">
<span class="mdl-layout-title">Sample</span>
<div class="mdl-layout-spacer"></div>
<nav class="mdl-navigation">
<a class="mdl-navigation__link smooth" href="#0">0</a>
<a class="mdl-navigation__link smooth" href="#1">1</a>
<a class="mdl-navigation__link smooth" href="#2">2</a>
<a class="mdl-navigation__link smooth" href="#3">3</a>
<a class="mdl-navigation__link smooth" href="#4">4</a>
</nav>
</div>
</header>

<!--Main contents -->
<main class="mdl-layout__content">
<ul class="ul-test">
<li id="0">0</li>
<li id="1">1</li>
<li id="2">2</li>
<li id="3">3</li>
<li id="4">4</li>
</ul>
</main>
</div>


Correct Scroll

---When smooth scroll starts from "top", scroll works correct.

---However if the goal of scroll is "top", scroll works correct.


  • From "top" to "#1"

  • From "top" to "#3"

  • From "#2" to "top"

  • etc..



Incorrect Scroll

---When smooth scroll dose not start from "top", scroll dosen't work correct.

---When leaving position and arriving position are same, scroll dosen't work incorrect.


  • From "#1" to "#2"

  • From "#2" to "#4"

  • From "#3" to "#3"

  • etc..



I have no idea why smooth scroll do not work correct.

Answer

The solution of this problem is here:
http://qiita.com/gonshi_com/items/33ac3df3ed98352c96b6#comment-87ad66f44229688fb638

jQuery's ".offset()" cannot get correct position with "zoom" property of css.

Solution is this:

var target = $( '#target' ).offset().top;

var target = $( '#target' ).get( 0 ).offsetTop
Comments