user3456188
user3456188

Reputation: 69

Set different offset to scrolltop when a specific link is clicked

I currently have the following code that works nicely and scrolls to the top of a div when a link is clicked...

$(function () {
  $('a[href*=#]:not([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) {
        $('html,body').animate({scrollTop: target.offset().top}, 1500);
        return false;
      }
    }
  });
});

However what I would like to do is that when a specific set of links are clicked (#topbannerlinks a) it scrolls to the top of the div but with a different offset e.g.

$("#topbannerlinks a").click(function(){
    $('html,body').animate({ scrollTop: target.offset().top -180 }, 1500);
});

Can I add build this function/if statement in to the above first function somehow?

I'm trying to do it this way becase I have a different height header on the target link page, and it doesnt scroll to the top correctly.

Upvotes: 1

Views: 421

Answers (1)

Stephan Muller
Stephan Muller

Reputation: 27610

You can check if a certain element also matches another selector by using .is(). For example this will return true if your link also matches #topBanner a and false if it's another link:

$(myLink).is('#topBanner a');

So inside your .click() function you can use $(this).is('#topBanner a') to do this check.

Instead of having the same animate function twice in your code, you can just set only the offset based on whether or not the link was in #topBanner and then always add the offset (whether it is 0 or 180)

if (target.length) {
    // set 180 if link is in #topBanner, otherwise 0
    var offset = $(this).is('#topBanner a') ? 180 : 0; 

    $('html,body').animate({scrollTop: target.offset().top - offset}, 1500);
    return false;
}

Upvotes: 1

Related Questions