I am new to web development and I recently discovered the revealing module pattern. But I am having problems implementing it in to my JS.
var navigation = (function(){
//chache DOM
var $navBar = $('.navBar');
var $navBtn = $('.navBar .btn');
var $section = $('.section');
var mobileNav = $('.navBarMobile');
//bind events
$('.navBar .btn').on('click', sectionScroll());
//$navBtn.on('click', sectionScroll()); wouldn't run
//select section via scroll pos.
function selectScroll(){
var windscroll = $(window).scrollTop();
if (windscroll >= 10)
{
$('.section').each(function(i)
{
if ($(this).offset().top -200 <= (windscroll))
{
$navBtn.removeClass('selected');
$navBtn.eq(i+6).addClass('selected');
$navBtn.eq(-i+5).addClass('selected');
}
});
}
}
//scroll to section via click
function sectionScroll(e){
e.preventDefault();
var target = $(this).find('a').attr('data-scroll');
var offset = $('[data-anchor=' + target +']').offset().top - 100;
TweenMax.to($('html, body').stop(), 1, {scrollTop: offset, delay: .36});
}
return {
selectScroll: selectScroll
};
})();
var main = function ()
{
$(window).scroll(function() { navigation.selectScroll(); }).scroll();
};
$(document).ready(main);
In my selectScroll function it wouldn't run correctly until I replaced "$navBtn" with "$('.navBar .btn')". Did I do something wrong when i declared the variables?
Also if I replace
$navBtn.on('click', sectionScroll());
with
$('.navBar .btn').on('click', sectionScroll());
the sectionScroll function kept giving me this error: Cannot read property 'preventDefault' of undefined
EDIT:
I found the problem thanks to @Bergi on this page. My question is now what would be the best way to use this soulution along with the revealing module pattern? Would it be putting the defer attribute on the JS :
<script type="text/javascript" src="js/app.js" defer></script>
or is there a better solution when using revealing module pattern?
The Problem is sectionScroll()
. It should be sectionScroll
without the parentheses.
With parens you are calling sectionScroll
and then pass it's return value
to on
. As you called it without arguments, parameter e
of sectionScroll
would be of value undefined
and you got the error.
Try this: $('.navBar .btn').on('click', sectionScroll);