Links on the page do not work

I have a problem with a link on one page. It works when I want to scroll down, but when I want to scroll up, it will stay in the same place. This is part of the code:

(function($){
/* Store the original positions */
var d1 = $('.one');
var d1orgtop = d1.position().top;
var d2 = $('.two');
var d2orgtop = d2.position().top;
var d3 = $('.three');
var d3orgtop = d3.position().top;
var d4 = $('.four');
var d4orgtop = d4.position().top;

/* respond to the scroll event */
$(window).scroll(function(){
    /* get the current scroll position */
    var st = $(window).scrollTop();

    /* change classes based on section positions */
    if (st >= d1orgtop) {
        d1.addClass('latched');
    } else {
        d1.removeClass('latched');
    }
    if (st >= d2orgtop) {
        d2.addClass('latched');
    } else {
        d2.removeClass('latched');
    }
    if (st >= d3orgtop) {
        d3.addClass('latched');
    } else {
        d3.removeClass('latched');
    }
    if (st >= d4orgtop) {
        d4.addClass('latched');
    } else {
        d4.removeClass('latched');
    }
});

And an example in JSFIDDLE JSFIDDLE

When I click href on top of the page, it scrolls down. But when I click href below, nothing happens. Where is my fault?

+4
source share
2 answers

Demo

- position:fixed .latched. , , , . jquery hack, .

$('a[href="#intro"]').on('click',function(){
  $(d1,d2,d3,d4).removeClass('latched');  
  //on click of #intro element you just remove latched class from all the elements
})
+4

, .

, . : https://jsfiddle.net/nft4oeab/3/

:

function scrollToAnchor(aid){
    var aTag = $("a[name='"+ aid +"']");
    $('html,body').animate({scrollTop: aTag.offset().top},'slow');
}

, .

+3

Source: https://habr.com/ru/post/1617065/


All Articles