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
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
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.