Cannot read property 'top' of undefined Jqueryjavascript - Stack Overflow

Probably this question has been answered many times before, but i can't find anything that related

Probably this question has been answered many times before, but i can't find anything that related to my code.

Everything works properly, when the menu nav is open, etc. the smooth scrolling works as well, except when i click the arrow-down to go the the next section, smooth scrolling doesnt work. I have been looking at it and trying to figure it out for a while but i am unable to do so.

I am still learning jquery and javascript. A full DEMO of this code in use can be found HERE. Open dev tools and you will see the errors in the console.

EDIT added..

.arrow-down-wrapper a[href^="#"]

to

$('nav.mobile-nav a[href^="#"], .arrow-down-wrapper a[href^="#"]').on('click', function (e) {
...
}

Smooth scrolling not works for the 'arrow-down', but i am still getting 'Uncaught TypeError: Cannot read property 'top' of undefined'

console.log(target); outputs the correct targets. #Home, #about, etc..

This is the code i have:

    //smooth transition to sctions when links in header are clicked

    function onScroll(event){
      var scrollPosition = $(document).scrollTop();
      $('nav.mobile-nav a').each(function () {
        var currentLink = $(this);
        var refElement = $(currentLink.attr("href"));
        if (refElement.position().top <= scrollPosition && refElement.position().top + refElement.height() > scrollPosition) {
          $('nav.mobile-nav a').removeClass("current");
          currentLink.addClass("current");
        }
        else{
          currentLink.removeClass("current");
        }
      });
    }

    $(document).ready(function () {
            $(document).on("scroll", onScroll);

            $('nav.mobile-nav a[href^="#"]').on('click', function (e) {
                e.preventDefault();
                $(document).off("scroll");

                $('nav.mobile-nav a').each(function () {
                    $(this).removeClass('current');
                });
                $(this).addClass('current');

                var target = this.hash;
                $target = $(target);
                $('html, body').stop().animate({
                    'scrollTop': $target.offset().top
                }, 1000, 'swing', function () {
                    window.location.hash = target;
                    $(document).on("scroll", onScroll);
                });
            });
        });

Probably this question has been answered many times before, but i can't find anything that related to my code.

Everything works properly, when the menu nav is open, etc. the smooth scrolling works as well, except when i click the arrow-down to go the the next section, smooth scrolling doesnt work. I have been looking at it and trying to figure it out for a while but i am unable to do so.

I am still learning jquery and javascript. A full DEMO of this code in use can be found HERE. Open dev tools and you will see the errors in the console.

EDIT added..

.arrow-down-wrapper a[href^="#"]

to

$('nav.mobile-nav a[href^="#"], .arrow-down-wrapper a[href^="#"]').on('click', function (e) {
...
}

Smooth scrolling not works for the 'arrow-down', but i am still getting 'Uncaught TypeError: Cannot read property 'top' of undefined'

console.log(target); outputs the correct targets. #Home, #about, etc..

This is the code i have:

    //smooth transition to sctions when links in header are clicked

    function onScroll(event){
      var scrollPosition = $(document).scrollTop();
      $('nav.mobile-nav a').each(function () {
        var currentLink = $(this);
        var refElement = $(currentLink.attr("href"));
        if (refElement.position().top <= scrollPosition && refElement.position().top + refElement.height() > scrollPosition) {
          $('nav.mobile-nav a').removeClass("current");
          currentLink.addClass("current");
        }
        else{
          currentLink.removeClass("current");
        }
      });
    }

    $(document).ready(function () {
            $(document).on("scroll", onScroll);

            $('nav.mobile-nav a[href^="#"]').on('click', function (e) {
                e.preventDefault();
                $(document).off("scroll");

                $('nav.mobile-nav a').each(function () {
                    $(this).removeClass('current');
                });
                $(this).addClass('current');

                var target = this.hash;
                $target = $(target);
                $('html, body').stop().animate({
                    'scrollTop': $target.offset().top
                }, 1000, 'swing', function () {
                    window.location.hash = target;
                    $(document).on("scroll", onScroll);
                });
            });
        });
Share Improve this question edited Jan 5, 2016 at 4:38 Guille asked Jan 5, 2016 at 3:39 GuilleGuille 6521 gold badge5 silver badges20 bronze badges 8
  • If the element on which the position is called does not exists then the error could e... – Arun P Johny Commented Jan 5, 2016 at 3:41
  • so log the value of currentLink.attr("href") - (console.log(currentLink.attr("href"))) and console.log(this.hash) before calling position to find out which element is causing the error – Arun P Johny Commented Jan 5, 2016 at 3:42
  • @ArunPJohny (console.log(currentLink.attr("href")) outputs, all three tags, #about, #home, #porfolio. and console.log(target) outputs, every tag i click on. #HOME, about, ...etc – Guille Commented Jan 5, 2016 at 4:41
  • before the error is thrown in the console which value is printed – Arun P Johny Commented Jan 5, 2016 at 4:54
  • 1 The problem is in your html, you have the following markup for the Contact link <a href="contact">Contact Us</a> You are missing the # in the href – Arun P Johny Commented Jan 5, 2016 at 5:00
 |  Show 3 more ments

3 Answers 3

Reset to default 1

The issue was that the code wasn't specific enough. The loop was iterating through all the items in the list, that is all the links that where #tags, and links to other pages. That is the reason i was getting the error of top not defined, that item it was looking for didn't exist. a[href^="#"' after adding that, loop only iterated the items with # ID tags.

Commented the changes i made

//smooth transition to sctions when links in header are clicked

    function onScroll(event){
      var scrollPosition = $(document).scrollTop();
      $('nav.mobile-nav a[href^="#"').each(function () { //added a[href^="#"] so that the loop only iterates over the elements with the ID tag
        var currentLink = $(this);
        var refElement = $(currentLink.attr("href"));
        console.log(currentLink.attr("href")); //log
        if (refElement.position().top <= scrollPosition && refElement.position().top + refElement.height() > scrollPosition) {
          $('nav.mobile-nav a').removeClass("current");
          currentLink.addClass("current");
        }
        else{
          currentLink.removeClass("current");
        }

      });
    }

    $(document).ready(function () {
            $(document).on("scroll", onScroll);

            $('nav.mobile-nav a[href^="#"], .arrow-down-wrapper a[href^="#"]').on('click', function (e) {
                e.preventDefault();
                $(document).off("scroll");

                $('nav.mobile-nav a').each(function () {
                    $(this).removeClass('current');
                });
                $(this).addClass('current');

                var target = this.hash;
                $target = $(target);
          console.log(target);
          $('html, body').stop().animate({
                    'scrollTop': $target.offset().top - 100
                }, 1000, 'swing', function () {
                    window.location.hash = target;
                    $(document).on("scroll", onScroll);
                });

            });
        });

That is a style so the value, in javascript, would need to be .style.top not just .top. That is why you are getting 'undefined'. There is no top property assigned to the object you are using.

I don't use jQuery but, in javascript, to retrieve the top property, you could do something like:

var a = document.getElementsByTagName('div')[0];
var b = a.style.top;
console.log(parseInt(b,10)); //cause b will be equal to 'nnpx' and parseInt removes the 'px'

However, this doesn't read any top value set in CSS. You need to set the value with javascript in order to read that. There is a way to read the value set in a CSS stylesheet but I don't recall how.

I don't actually get the problem. Opening the dev tools i have some errors but the smooth scroll on your website works quite fine for me.

Have a look at this jsfiddle i made:

https://jsfiddle/p4x3d2dn/1/

HTML

<ul class="nav">
  <li><a class="scroll" href="#section_home">Home</a></li>
  <li><a class="scroll" href="#section_about">About</a></li>
  <li><a class="scroll" href="#section_team">Team</a></li>
  <li><a class="scroll" href="#section_gallery">Gallery</a></li>
  <li><a class="scroll" href="#section_contact">Contact</a></li>
</ul>

<section id="section_home">
  <h1>Home</h1>
</section>
<section id="section_about">
  <h1>About</h1>
</section>
<section id="section_team">
  <h1>Team</h1>
</section>
<section id="section_gallery">
  <h1>Gallery</h1>
</section>
<section id="section_contact">
  <h1>Contact</h1>
</section>

Adding other links (such as a scroll down arrow) is just a matter of adding the correct href attribute to the .scroll tag:

<a class="scroll" href="#section_whatever_you_want">
    <i class="fa fa-chevron-down"></i>
</a>

A slightly different approach must be taken if you have custom generated sections and you are not in control of the DOM

This is all the javascript you need:

$(document).ready(function() {

  $(".scroll").on("click", function() {
    //event.preventDefault();
    var el = $(this).attr("href");
    $('html, body').animate({
      scrollTop: $(el).offset().top
    }, 2000);
  });

});

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745568836a4633556.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信