Jordy Senssen
Jordy Senssen

Reputation: 171

Error Scrolltop: top not defined

I get the following error

Uncaught TypeError: Cannot read property 'top' of undefined.

It's talking about the top that is standing in the line: $(html, body).. , 1000, function but I really have no clue how to fix this error. I have tried multiple other posts with a fairly similar problem, but none of them fixed my problem so far.

// Menu Scroll to content and Active menu
var lastId,
  topMenu = $("#menu"),
  topMenuHeight = topMenu.outerHeight() + 145,
  menuItems = topMenu.find("a"),
  scrollItems = menuItems.map(function() {
    var item = $($(this).attr("href"));
    if (item.length) {
      return item;
    }
  });

$('a[href*=#]').bind('click', function(e) {
  e.preventDefault();

  var target = $(this).attr("href");

  $('html, body').stop().animate({
    scrollTop: $(target).offset().top - 60
  }, 1000, function() {});

  return false;
});

$(window).scroll(function() {
  var fromTop = $(this).scrollTop() + topMenuHeight;
  var cur = scrollItems.map(function() {
    if ($(this).offset().top < fromTop)
      return this;
  });

  cur = cur[cur.length - 1];
  var id = cur && cur.length ? cur[0].id : "";

  if (lastId !== id) {
    lastId = id;
    menuItems
      .parent().removeClass("active")
      .end().filter("[href=#" + id + "]").parent().addClass("active");
  }
});

Upvotes: 4

Views: 7060

Answers (1)

BenG
BenG

Reputation: 15154

you are trying to get offset from the .attr('href').

try removing the .attr('href');.

var target = $(this);

$('html, body').stop().animate({ scrollTop: $(target).offset().top -60 }, 1000, function() {

});

OR

As your selector has $('a[href*=#]') it could be that the href contains more than just #id but /foo/bar#id. therefore try:-

var target = $(this).attr("href").split('#')[1];

$('html, body').stop().animate({
    scrollTop: $('#' + target).offset().top - 60
  }, 1000, function() {});

Upvotes: 3

Related Questions