1. 程式人生 > >Same page navigation in MeteorJS

Same page navigation in MeteorJS

We currently live in a world dominated by JavaScript. While JS might not be my most favorite language, I am practical enough to realize that ignoring it isn’t a sound approach to being an efficient software professional. Having said that, I still get the freedom to pick the JS framework that strikes my fancy the most. In my case, I like

Meteor. I have been experimenting with the framework for some time now, one of the challenges that I faced was same page navigation in MeteorJS.

This article assumes some basic knowledge of MeteorJS. If you need some head start, check this quick tutorial

Problem statement

MeteorJS is a very practical framework for this day and age. However, due to the structure of the framework, it can be challenging to do same page navigation in MeteorJS using typical approaches like

anchor tags. This means it could be challenging to navigate to other locations on the same page in your MeteorJS project. This can be useful if ,for example, your main page consists of multiple sections, and you want the user to be able to jump ahead to specific sections using links without manually scrolling to them. The reason why anchor tags don’t work is due to the
template
 system that Meteor uses combined with Iron router, which Meteor uses for it’s routing. A solution was suggested here however it didn’t fully work for me.

How to do same page navigation in MeteorJS smoothly?

You can achieve a smooth navigation on the same page with a visual effect that is fancier than anchor tags by using JQuery, which comes prepackaged with MeteorJS.

First, you write a JavaScript function utilizing JQuery to animate scrolling to a specific location based on the location’s HTML ID:

var scrollFunction = function(idstring) {
  $('html, body').animate({
    scrollTop: $(idstring).offset().top
  }, 1000);
};

Second, use Meteor’s template events to activate the JQuery scrolling function when a desired link is clicked on. For our example, let’s assume a template called options includes links that are supposed to point to other positions on the same page , and that the links themselves have the HTML ids contactlink, mainlink , and aboutlink.

Template.options.events({
  "click #mainlink": function() { 
    scrollFunction('#main');
  },

  "click #aboutlink": function() {
    scrollFunction('#about');
  },

  "click #contactlink": function() {
    scrollFunction('#contact');
  },
});

The code above means that when the user clicks on the HTML element with ID ‘contact link’ which exists in the options template, JQuery will kick in and will animate scrolling to the HTML element with ID ‘contact’ which may even exist in a different template but on the same overall page.