4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

hashchangeイベントとscrollYの不思議な挙動

Posted at

hashchangeイベントで取得したwindow.scrollYおよびwindow.pageYOffsetなど、現在のスクロールの値が期待とだいぶ違う。


デモ

  1. ハッシュチェンジしてください
  2. 適当にスクロールしてください
  3. ボタンをクリックして現在のスクロール値を参照してください
  4. ブラウザの「戻る」をします
  5. 再取得するので、現在のスクロール値を参照するはずがハッシュチェンジ以前の値を取得します
  6. ブラウザの「進む」をします
  7. さきほど「戻る」をした瞬間のスクロール値が取得されます
  8. ...なぜだろう

$ ->
  $input = $('input')
  
  $('button').on 'click', ->
    $input.val window.pageYOffset # => 現在のscrollY
    
  $(window).on 'hashchange', ->
    $input.val window.pageYOffset # => hashchangeする前のscrollYが返される
    window.scrollTo 0, 0

...なぜだ?!

ChromeでもFirefoxでも同じだったから仕様っぽい。

hashchangeでも現在のきちんとした値を取得したいのだけど、無理なんだろうか。。。

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?