I am creating a new site that contains multiple sections. Each section has a header that contains an 1 heading (h1). Also each section has an id
attribute.
What I am looking for is how I can add a minimal parallax effect to the headers for each section. When the section is in the viewport, it should start with animate the margin-top
of the header for like an x amount of pixels, like 5 or 10px.
I would like to check which section is in the viewport of the browser, and if so, begin the parallax animation. If it is possible, without any plugin. How should I do this?
I came up with the following:
$(window).scroll(function() {
// Get the offset of the window from the top of page
var windowPos = $(window).scrollTop();
$('.main').find('section').each(function() {
var anchorId = $(this);
var target = $(anchorId.attr("id"));
var offsetTop = target.position().top;
if (offsetTop <= windowPos && offsetTop + target.height() > windowPos) {
console.log(this);
// Parallax function here
}
});
});
Unfortunately, I receive the error: Uncaught TypeError: Cannot read property 'top' of undefined
.
So, I would like that the code is returning the id of the section, that is then in the viewport visible. And start then the animation the header for that section.
Thank you in advance. Live demo here: http://codepen.io/anon/pen/xZwpzX?editors=101