Search code examples
javascriptmeteoriron-router

Using iron-router to go to a certain id section of the page (url#portion) in Meteor.js


I have routes set up with iron-router that make sure the page goes to the top of the page:

Router.route('/services', {
    name: 'services',
    template: 'services',
  onAfterAction: function () {
          scrollTop();
  }  
});

function scrollTop() {
    window.scroll(0, 0);
}

However, if I am on another route, and I have a link like /services#thisid

it will still take me to the top of the page (not to the portion of the page with the id=thisid).

Is there a way to get around this?


Solution

  • This should address your issue both for this issue and your layout override question.

    Router.configure({
      layoutTemplate: 'main',
      onAfterAction: function(){
        console.log('hash', this.params.hash);
        if(!this.params.hash){
          scrollTop();
        }
      }
    });
    Router.route('/services', {
      name: 'services',
      template: 'services',
    });
    
    Router.route('/inquiry', {
      name: 'inquiry',
      template: 'inquiry',
      layoutTemplate: 'alternate'
    });
    

    The check for this.params.hash ensures that there is no value for the hash before executing the scrollTop. The layoutTemplate on the inquiry route overrides the layout while still respecting the global onAfterAction.