scrollTop: $(window.location.hash).offset().top scrolling to the end of the element?
Hi jQuery forum,
im pretty new to jQuery and usually just doing PHP/HTML/CSS things.
I´ve googled and tried this many many hours in the last 2 days but i cant get it working.
What i want to do: SmoothScrolling on same-page-links (working) and SmoothScrolling on new-page-links ("half-working").
My Code for same-page-links:
- $(document).ready(function() {
- $('a[href*=#]').click(function() {
- if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
- &&location.hostname == this.hostname) {
- var $target = $(this.hash);
- $target = $target.length && $target || $('[name=' + this.hash.slice(1) +']');
- if ($target.length) {
- var targetOffset = $target.offset().top;
- alert(targetOffset);
- $('html,body').animate({scrollTop: targetOffset}, 1000);
- return false;
- }
- }
- });
- });
To be honest I still dont know what line 6 exactly does...
My code for new-page-links:
- $=jQuery;
- /*
- if (window.location.hash) scroll(0, 0);
- setTimeout(function() {
- scroll(0, 0);
- }, 1);
- */
- $(document).ready(function() {
- if (window.location.hash) {
- alert($(window.location.hash).offset().top);
- $('html, body').delay(500).animate({
- scrollTop: $(window.location.hash).offset().top
- }, 1000);
- }
- });
Im alerting the offsets for both methods and getting different values.
Example (same element): 2154.1875 pixels from top (opening link in new tab) and 2773.1875 pixels from top (clicking on same-page-link).
If I open the page in a new tab it always scrolls to the bottom of the element and Im not able to get why after these 2 days. I´ve tested it with different elements -> the difference between those 2 methods are changing. Sometimes its about 600px difference, sometimes 400px but its NOT nearly the height of the elements beeing scrolled to.
I dont get it. Could someone point me in the right direction please?