From this post we are going to
learn how to create a single page website layout using only html and jquery.All we need is your favorite code editor and jQuery library file.
We are going to use html
div
tags to separate the pages as sections. Here we are using fixed header to show the section links.
just separate your various page contents in various
section divs
and header content within header div.
In css we just assign, size of the div. I mean size of the page. In header page link, we need to mention the
section id
to bring it to top when user click on that page.
Then we can write our
javascript code
like below.
var from = $("#header").height();
$(document).ready(function () {
$(".link:first").css("top", from + 'px');
});
$(".jumper").on("click", function (e) {
e.preventDefault();
$("body, html").animate({
scrollTop: $($(this).attr('href')).offset().top - from
});
});
Here we are using jQuery method
.animate()
to
scroll
the page. In this we are using
scrollTop
attribute to scroll the clicked section to the top of the page.
In the above code we used minus some value in
scrollTop
attribute of
.animate()
method. Because in this example we are using
fixed header. If we use
scrollTop
attribute like below,
scrollTop: $($(this).attr('href')).offset().top
top of our
section div
contents will hide behind
header div
. So, we get the
height of header div
using,
var from = $("#header").height();
and reduce it from the top like this,
scrollTop: $($(this).attr('href')).offset().top - from
By this, our
section div
content will display below to
header div
.
have you seen this line in the above code? could you guess why we using this?
$(".link:first").css("top", from + 'px');
Already I told, we are using fixed header for menu. So, the first section div will hide behind that header div. For that, we get the header div's height and assign that height value to first section div.
For example, if
var from = $("#header").height();
return 85 to variable from, when we use this below code in document ready,
$(".link:first").css("top", from + 'px');
our first section div's css looks like,
.link:first {
top:85px;
}
Here is the DEMO