-1

I am getting Uncaught TypeError: Cannot read property 'offset' of undefined

Before that i was getting same exception for 'top' from same block. I fixed it in one way now, I am getting the error with 'offset'.

Here is my code.

var ssSmoothScroll = function() {

    $('.smoothscroll').on('click', function (e) {
        if (this.hash !== "" && this.pathname == window.location.pathname) {
        var target = this.hash;
        // $target    = $(target);


        e.preventDefault();
        e.stopPropagation();

        var topOffset = 0; //#top should default to 0 so no need to calculate the difference between top and top :)
            if (target != "#top") { //If the target is not "#top", then calculate topOffset 
            var topOffset = $(target).offset().top;
            }
        }
        else{
                var target = this.hash,
                $target    = $(target);

                e.preventDefault();
                e.stopPropagation();

        }
        $('html, body').stop().animate({
            'scrollTop': $target.offset().top
        }, cfg.scrollDuration, 'swing', function () {
            window.location.hash = target;
        });
    });
};

Any help is appreciated :)

1
  • I think this refers to event argument. according to this page @Dez
    – Saeed
    May 24, 2018 at 16:06

2 Answers 2

0

Because you define $target inside the else statement so if it does not go into the else it is undefined.

You need to set $target outside of the else

if (target != "#top") {
  // you do not set it here
  ...
else{
  var target = this.hash,  // <-- not sure why you are declaring target again....
  $target    = $(target); // you set it here
  ...
}
0

Try this code instead, I think this works

var ssSmoothScroll = function() {
  $(".smoothscroll").on("click", function(e) {
    if (this.hash !== "" && this.pathname == window.location.pathname) {
      var target = this.hash,
        $target = $(target);
      // $target    = $(target);

      e.preventDefault();
      e.stopPropagation();

      var topOffset = 0; //#top should default to 0 so no need to calculate the difference between top and top :)
      if (target != "#top") {
        //If the target is not "#top", then calculate topOffset
        topOffset = $(target).offset().top;
      }
      $("html, body")
        .stop()
        .animate(
          {
            scrollTop: $target.offset().top
          },
          cfg.scrollDuration,
          "swing",
          function() {
            window.location.hash = target;
          }
        );
    }
  });
};

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.