Mitsuhiko Shimomura Mitsuhiko Shimomura - 1 year ago 147
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):

Some important parts of the code.

Smooth Scroll:

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;

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>

<!--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>

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 Source

The solution of this problem is here:

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download