0

I have an accordion. I will like to scroll to the anchor name inside the accordion when the anchor link is clicked. Sample url: http://swagatobhatta.com/accordion.html

I am getting an error as in Cannot read property 'top' of undefined

I have looked throughout the google and also here in stackoverflow. I have pretty much applied all the solutions given. Still I can not solve this

code:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Testing accordion</title>
<link rel="stylesheet" type="text/css" href="test.css" />
</head>
<body>
Hello world
<a href="#anchor1">Anchor 1</a>
<br/>
<a href="#anchor2">Anchor 2</a>
<div>
Enthusiastically reconceptualize wireless technologies rather than pandemic e-business. Collaboratively deliver cross functional core competencies after economically sound services. Proactively build resource maximizing human capital before client-centric best practices. Efficiently simplify multifunctional functionalities and team building materials. Credibly morph cross-media partnerships without diverse quality vectors.</div>
<div class="accordionModule  ">
  <h3 class="title"> Credibly initiate market positioning e-commerce after web-enabled core competencies. Dramatically. </h3>
  <div class="panels">
    <div class="accordionPanel"> <a href="#" class="trigger">
      <h4 class="accordionTitle">Loreum 1</h4>
      </a>
      <div class="content richTextModule">
        <p>Efficiently evolve bricks-and-clicks human capital for focused intellectual capital. Compellingly brand state of the art information vis-a-vis backend channels. Appropriately empower high-payoff schemas whereas bricks-and-clicks processes. <a name="globally"></a>Globally drive resource sucking leadership and wireless products. Assertively monetize viral testing procedures without bleeding-edge e-markets.</p>
      </div>
    </div>
    <div class="accordionPanel"> <a href="#" class="trigger">
      <h4 class="accordionTitle">Test Links</h4>
      </a>
      <div class="content richTextModule">
        <p>This is an external link to<a href="http://swagatobhatta.com/accordion.html">Where am i</a></p>
        <p>&nbsp;</p>
        <p>My</p>
      </div>
    </div>
    <div class="accordionPanel"> <a href="#" class="trigger">
      <h4 class="accordionTitle">Internal anchor test</h4>
      </a>
      <div class="content richTextModule">
        <p>This is <a href="http://swagatobhatta.com/accordion.html">internal anchor test</a></p>
        <p><a name="anchor1"></a>anchor&nbsp;</p>
      </div>
    </div>
    <div class="accordionPanel"> <a href="#" class="trigger">
      <h4 class="accordionTitle">Anchor inside</h4>
      </a>
      <div class="content richTextModule">
           <p>&nbsp;</p>
        <p>&nbsp;</p>
        <p>Hello <a name="anchor2"></a>world</p>
        <p>&nbsp;</p>
        <p>&nbsp;</p>

      </div>
    </div>
  </div>
</div>

<div>
Interactively brand professional convergence vis-a-vis just in time niches. Credibly seize wireless channels rather than corporate intellectual capital. Seamlessly recaptiualize customer directed products without cross functional supply chains. Rapidiously administrate progressive technology before cross functional core competencies. Objectively orchestrate integrated total linkage before dynamic schemas.


Enthusiastically reconceptualize wireless technologies rather than pandemic e-business. Collaboratively deliver cross functional core competencies after 
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
(function (_this, $) {
    _this.accordionSpeed = 400;
    _this.initialise = function () {
        $(function () {
            bindAccordionTriggers();
        });

        return _this;
    }

    var bindAccordionTriggers = function() {
        $('.accordionModule .accordionPanel .trigger').on('click', function(e) {
            e.preventDefault();

            var $parentPanel = $(this).parents('.accordionPanel');

            if( $parentPanel.hasClass('open') ) {
                $parentPanel.removeClass('open');
                $parentPanel.find('.content').slideUp(_this.accordionSpeed);
            }
            else {
                var $module = $(this).parents('.accordionModule');
                if($module.hasClass('open-single-only')) {
                    var $openPanel = $module.find('.accordionPanel.open');
                    $openPanel.find('.content').slideUp();
                    $openPanel.removeClass('open');
                }

                $parentPanel.find('.content').slideDown(_this.accordionSpeed);
                $parentPanel.addClass('open');
            }
        });


        function scrollToAnchor(aid){
            var aTag = $("a[name='"+ aid +"']");
            $('html,body').animate({scrollTop: aTag.offset().top},'slow');
        }



        $(window).on('load hashchange',function(event){
            var hash = window.location.hash;
            var hashName = hash && hash.replace('#','');
                event.preventDefault();

            if (hashName) {
                //document.getElementsByName ("#anchor1").scrollIntoView();
                scrollToAnchor('hashName');

                $('.accordionModule .accordionPanel .content a').filter(function(){
                    //return this.hash === hash;
                    return this.name === hashName;
                }).closest('.accordionPanel').find('.trigger').click()

            }
        });

    }

    // Initialise & assign to global scope
    window.AccordionModule = _this.initialise();
})(window.AccordionModule || {}, jQuery);
</script>
</body>
</html>
1
  • Make sure that aTag is what you are expecting. Commented Oct 9, 2015 at 3:08

2 Answers 2

1

Instead of:

<p><a name="anchor1"></a>anchor&nbsp;</p>
<p>Hello <a name="anchor2"></a>world</p> 

try to have:

<p id="anchor1">ANCHOR 1 HERE</p>
<p id="anchor2">ANCHOR 2 HERE</p> 

Also the script for "scroll to anchor" is a lot simpler than what you currently have. Here is a snippet:

jQuery(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
        }, 1000);
        return false;
      }
    }
  });
});

DEMO:

http://codepen.io/Himechi90/pen/wKepep

Good luck!

0

Try the below code.

Your scrollToAnchor('hashName'); is wrong...you should assign like scrollToAnchor(hashName);

Also you can find the correct way of implantation here

(function(_this, $) {
  _this.accordionSpeed = 400;
  _this.initialise = function() {
    $(function() {
      bindAccordionTriggers();
    });

    return _this;
  }

  var bindAccordionTriggers = function() {
    $('.accordionModule .accordionPanel .trigger').on('click', function(e) {
      e.preventDefault();

      var $parentPanel = $(this).parents('.accordionPanel');

      if ($parentPanel.hasClass('open')) {
        $parentPanel.removeClass('open');
        $parentPanel.find('.content').slideUp(_this.accordionSpeed);
      } else {
        var $module = $(this).parents('.accordionModule');
        if ($module.hasClass('open-single-only')) {
          var $openPanel = $module.find('.accordionPanel.open');
          $openPanel.find('.content').slideUp();
          $openPanel.removeClass('open');
        }

        $parentPanel.find('.content').slideDown(_this.accordionSpeed);
        $parentPanel.addClass('open');
      }
    });


    function scrollToAnchor(aid) {
      console.log(aid);
      var aTag = $("a[name='" + aid + "']");
      $('body').animate({
        scrollTop: aTag.offset().top
      }, 1000)
    }



    $(window).on('load hashchange', function(event) {
      var hash = window.location.hash;
      var hashName = hash && hash.replace('#', '');
      event.preventDefault();

      if (hashName) {
        //document.getElementsByName ("#anchor1").scrollIntoView();

        scrollToAnchor(hashName);

        $('.accordionModule .accordionPanel .content a').filter(function() {
          //return this.hash === hash;
          return this.name === hashName;
        }).closest('.accordionPanel').find('.trigger').click();

      }
    });

  }

  // Initialise & assign to global scope
  window.AccordionModule = _this.initialise();
})(window.AccordionModule || {}, jQuery);
<!doctype html>
<html>

<head>
  <meta charset="utf-8">
  <title>Testing accordion</title>
  <link rel="stylesheet" type="text/css" href="test.css" />
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>

<body>
  Hello world
  <a href="#anchor1">Anchor 1</a>
  <br/>
  <a href="#anchor2">Anchor 2</a>



  <div>
    Interactively brand professional convergence vis-a-vis just in time niches. Credibly seize wireless channels rather than corporate intellectual capital. Seamlessly recaptiualize customer directed products without cross functional supply chains. Rapidiously
    administrate progressive technology before cross functional core competencies. Objectively orchestrate integrated total linkage before dynamic schemas. Compellingly enable user friendly core competencies rather than strategic architectures. Authoritatively
    customize unique quality vectors through collaborative paradigms. Proactively incubate integrated applications with stand-alone networks. Energistically re-engineer viral interfaces vis-a-vis high-payoff relationships. Seamlessly plagiarize pandemic
    corporate intellectual capital. Seamlessly recaptiualize customer directed products without cross functional supply chains. Rapidiously administrate progressive technology before cross functional core competencies. Objectively orchestrate integrated
    total linkage before dynamic schemas. Compellingly enable user friendly core competencies rather than strategic architectures. Authoritatively customize unique quality vectors through collaborative paradigms. Proactively incubate integrated applications
    with stand-alone networks. Energistically re-engineer viral interfaces vis-a-vis high-payoff relationships. Seamlessly plagiarize pandemic internal or "organic" sources via backward-compatible customer service. Assertively exploit distinctive manufactured
    products before adaptive initiatives. Continually harness premier leadership skills via cost effective synergy. Holisticly streamline efficient results after customer directed synergy. Rapidiously embrace cross-unit ideas for backend e-markets. Credibly
    expedite effective collaboration and idea-sharing for superior relationships. Dramatically underwhelm client-based e-services with transparent services. Monotonectally evisculate just in time benefits without revolutionary quality vectors. Interactively
    incubate multidisciplinary sources and intermandated relationships. Continually evisculate multidisciplinary infomediaries and collaborative partnerships. Quickly envisioneer one-to-one total linkage with future-proof testing procedures. Globally
    reintermediate backend mindshare before excellent systems. Phosfluorescently integrate front-end supply chains via corporate technology. Interactively monetize global leadership before standardized functionalities. Energistically drive covalent synergy
    with virtual schemas. Assertively morph one-to-one mindshare without reliable synergy. Intrinsicly exploit superior core competencies without intuitive experiences. Assertively promote mission-critical technologies and dynamic initiatives. Rapidiously
    disseminate turnkey bandwidth before virtual leadership. Continually embrace future-proof materials with emerging vortals. Continually fashion next-generation schemas vis-a-vis cross-platform benefits. Completely conceptualize granular action items
    and parallel initiatives. Monotonectally reinvent frictionless action items with error-free alignments. Interactively repurpose sticky materials through value-added strategic theme areas. Seamlessly enable ethical niches after one-to-one technology.
    Objectively benchmark proactive content and best-of-breed platforms. Completely leverage existing customized infomediaries via resource maximizing manufactured products. Professionally implement impactful synergy rather than exceptional potentialities.
    Interactively coordinate customer directed products vis-a-vis real-time quality vectors. Synergistically transition market positioning technology and proactive total linkage. Interactively visualize e-business interfaces via innovative expertise.
    Uniquely exploit tactical process improvements and progressive platforms. Authoritatively seize resource sucking platforms before end-to-end partnerships. Compellingly administrate premier niches after bricks-and-clicks expertise. Monotonectally administrate
    real-time e-business rather than focused ideas. Compellingly evisculate bleeding-edge web-readiness vis-a-vis just in time internal or "organic" sources. Intrinsicly impact multimedia based architectures whereas high standards in networks. Globally
    fabricate high standards in communities rather than customized experiences. Objectively visualize intuitive leadership skills and resource-leveling results. Competently productivate resource maximizing products and multimedia based solutions. Dramatically
    enhance high-quality expertise before market-driven resources. Intrinsicly myocardinate pandemic e-tailers for timely e-markets. Conveniently incentivize prospective schemas vis-a-vis standards compliant e-services. Interactively maintain extensive
    communities before high-quality schemas. Uniquely empower seamless deliverables rather than ubiquitous web-readiness. Interactively mesh distinctive process improvements with collaborative schemas. Enthusiastically reconceptualize wireless technologies
    rather than pandemic e-business. Collaboratively deliver cross functional core competencies after economically sound services. Proactively build resource maximizing human capital before client-centric best practices. Efficiently simplify multifunctional
    functionalities and team building materials. Credibly morph cross-media partnerships without diverse quality vectors. Continually integrate one-to-one communities vis-a-vis unique processes. Completely.Interactively brand professional convergence
    vis-a-vis just in time niches. Credibly seize wireless channels rather than corporate intellectual capital. Seamlessly recaptiualize customer directed products without cross functional supply chains. Rapidiously administrate progressive technology
    before cross functional core competencies. Objectively orchestrate integrated total linkage before dynamic schemas. Compellingly enable user friendly core competencies rather than strategic architectures. Authoritatively customize unique quality vectors
    through collaborative paradigms. Proactively incubate integrated applications with stand-alone networks. Energistically re-engineer viral interfaces vis-a-vis high-payoff relationships. Seamlessly plagiarize pandemic internal or "organic" sources
    via backward-compatible customer service. Assertively exploit distinctive manufactured products before adaptive initiatives. Continually harness premier leadership skills via cost effective synergy. Holisticly streamline efficient results after customer
    directed synergy. Rapidiously embrace cross-unit ideas for backend e-markets. Credibly expedite effective collaboration and idea-sharing for superior relationships. Dramatically underwhelm client-based e-services with transparent services. Monotonectally
    evisculate just in time benefits without revolutionary quality vectors. Interactively incubate multidisciplinary sour
  </div>
  <div class="accordionModule  ">
    <h3 class="title"> Credibly initiate market positioning e-commerce after web-enabled core competencies. Dramatically. </h3>
    <div class="panels">
      <div class="accordionPanel">
        <a href="#" class="trigger">
          <h4 class="accordionTitle">Loreum 1</h4>
        </a>
        <div class="content richTextModule">
          <p>Efficiently evolve bricks-and-clicks human capital for focused intellectual capital. Compellingly brand state of the art information vis-a-vis backend channels. Appropriately empower high-payoff schemas whereas bricks-and-clicks processes.
            <a name="globally"></a>Globally drive resource sucking leadership and wireless products. Assertively monetize viral testing procedures without bleeding-edge e-markets.</p>
        </div>
      </div>
      <div class="accordionPanel">
        <a href="#" class="trigger">
          <h4 class="accordionTitle">Test Links</h4>
        </a>
        <div class="content richTextModule">
          <p>This is an external link to<a href="http://swagatobhatta.com/accordion.html">Where am i</a>
          </p>
          <p>&nbsp;</p>
          <p>My</p>
        </div>
      </div>
      <div class="accordionPanel">
        <a href="#" class="trigger">
          <h4 class="accordionTitle">Internal anchor test</h4>
        </a>
        <div class="content richTextModule">
          <p>This is <a href="http://swagatobhatta.com/accordion.html">internal anchor test</a>
          </p>
          <p>
            <a name="anchor1"></a>anchor&nbsp;</p>
        </div>
      </div>
      <div class="accordionPanel">
        <a href="#" class="trigger">
          <h4 class="accordionTitle">Anchor inside</h4>
        </a>
        <div class="content richTextModule">
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>Hello
            <a name="anchor2"></a>world</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
        </div>
      </div>
    </div>
  </div>
  <div>
    Interactively brand professional convergence vis-a-vis just in time niches. Credibly seize wireless channels rather than corporate intellectual capital. Seamlessly recaptiualize customer directed products without cross functional supply chains. Rapidiously
    administrate progressive technology before cross functional core competencies. Objectively orchestrate integrated total linkage before dynamic schemas. Compellingly enable user friendly core competencies rather than strategic architectures. Authoritatively
    customize unique quality vectors through collaborative paradigms. Proactively incubate integrated applications with stand-alone networks. Energistically re-engineer viral interfaces vis-a-vis high-payoff relationships. Seamlessly plagiarize pandemic
    internal or "organic" sources via backward-compatible customer service. Assertively exploit distinctive manufactured products before adaptive initiatives. Continually harness premier leadership skills via cost effective synergy. Holisticly streamline
    efficient results after customer directed synergy. Rapidiously embrace cross-unit ideas for backend e-markets. Credibly expedite effective collaboration and idea-sharing for superior relationships. Dramatically underwhelm client-based e-services with
    Interactively monetize global leadership before standardized functionalities. Energistically drive covalent synergy with virtual schemas. Assertively morph one-to-one mindshare without reliable synergy. Intrinsicly exploit superior core competencies
    without intuitive experiences. Assertively promote mission-critical technologies and dynamic initiatives. Rapidiously disseminate turnkey bandwidth before virtual leadership. Continually embrace future-proof materials with emerging vortals. Continually
    fashion next-generation schemas vis-a-vis cross-platform benefits. Completely conceptualize granular action items and parallel initiatives. Monotonectally reinvent frictionless action items with error-free alignments. Interactively repurpose sticky
    materials through value-added strategic theme areas. Seamlessly enable ethical niches after one-to-one technology. Objectively benchmark proactive content and best-of-breed platforms. Completely leverage existing customized infomediaries via resource
    impact multimedia based architectures whereas high standards in networks. Globally fabricate high standards in communities rather than customized experiences. Objectively visualize intuitive leadership skills and resource-leveling results. Competently
    productivate resource maximizing products and multimedia based solutions. Dramatically enhance high-quality expertise before market-driven resources. Intrinsicly myocardinate pandemic e-tailers for timely e-markets. Conveniently incentivize prospective
  </div>
</body>

</html>

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