ClubCola
ClubCola

Reputation: 69

jQuery - scroll to top with an offset

The function

var navigationFn = {
goToSection: function(id,offset) {
    if ($(offset)=="") {var offset = -10;}
    $('html, body').animate({
        scrollTop: $(id).offset().top + offset
    }, 1500);
  }
}

should move the user to an id with a special offset. If there is no specified offset, it should be -10 as default.

This works fine for me.

navigationFn.goToSection('#id',-70);

But I have several "old" calls like

navigationFn.goToSection('#id');

They bring me to the top of the html document, not to the id.

Is it possible to use both calls without changing the old ones?

Upvotes: 0

Views: 24

Answers (1)

void
void

Reputation: 36703

offset is not a jQuery Object but instead it is a number type function argument so you do not need $(offset) or something.

Just do offset = offset || -10;

This will set offset to -10 if not passed in the function

var navigationFn = {
goToSection: function(id,offset) {
    var offset = offset || -10;
    $('html, body').animate({
        scrollTop: $(id).offset().top + offset
    }, 1500);
  }
}

Upvotes: 3

Related Questions