2

This is the weirdest thing. I have the following javascript code, which causes my page to scroll to a specific location on click...

$('.whyattend').on('click', function (e) {
    e.preventDefault();
    $('#s4-workspace').animate({ scrollTop: $('#whyattend').offset().top });
});

When I click the first time it scrolls to my location, but when I click the same link a second time, it scrolls all the way back to the top of the page. It's doing this toggle thing. How can I avoid that so that it stays at the right page location the first click, second click, etc... until I decide to click a completely different link?

Thanks!

  • add a console.log( $('#whyattend').offset().top) and check if thats correct – Danny '365CSI' Engelman Dec 22 '15 at 20:17
  • That value changes on every click. First and third click are 2675.897 and second and fourth click are 0.0 – klewis Dec 22 '15 at 20:22
  • So .. scrollTop:0 will...scroll to the top of your page... – Danny '365CSI' Engelman Dec 22 '15 at 20:40
2

I think I discovered my issue and a potential solution..Using position() In my case the offset is not relative to the ( #s4-workspace), but relative to a child element that has a fixed position.

$('#s4-workspace').animate({ scrollTop: $('#target').position().top }, 500);

My target is inside of child container main...

<div id="#s4-workspace">

    <div id="main">
       <a href="#target">scroll to target and stay there</a>
       //...
       <div id="target">scroll to this position</div>
    </div>

</div>

...and #main has a position:fixed property applied to it.

This was a good learning exercise in knowing when to apply offset() and when to apply position().

Awesome!

1

It will be less weird if you do:

window.whyattendOffset=$('#whyattend').offset().top;
$('.whyattend').on('click', function (e) {
    e.preventDefault();
    $('#s4-workspace').animate({ scrollTop: window.whyattendOffset });
});

disclaimer.. sticking it on the window context so it works, I do not know your other code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.