Geeks With Blogs

@neh123us
  • neh123us T4 sould be your outsourcing strategy https://t.co/1ZceCUKWKE T4 - The Insource Code Monkey about 451 days ago
  • neh123us Had a need for Dynamic Views in MVC today. Wanted to use a Partial view on two different views with different ViewModels about 500 days ago

News Google

Nick Harrison Blog<Nick>.Next()

This snippet will add a list of links to every named anchor in your web page. Each link will have an associated click event handler to animate scrolling to that section.

I hope you find this useful.

First we build up our links. We use a jQury selector to find all of the anchor tags with a name attribute:

 

var toc = "";

$("a[name]").each(function (index, e) {

toc += "<li><a href='#' onclick=\"scrollToAnchor('"

+$(e).prop("name")+"')\">" + $(e).prop("name") + "</li>";

});

 

 

If you are familiar with jsRender, it will make building up the string a lot easier.

Once we have our content, we can add it to the page. We also wire up the scroll event hander so that our table of contents will always be visible:


if (toc.length > 0) {

$("#toc").html(toc);

var $scrollingDiv = $("#toc");

$(window).scroll(function () {

$scrollingDiv

                .stop()

                .animate({ "marginTop": ($(window).scrollTop() + 30) + "px" });

});

}

 

The scroollToAnchor function is simple and useful in other contexts as well:

function scrollToAnchor(aid) {

var aTag = $("a[name='" + aid + "']");

$('html,body') .animate({ scrollTop: aTag.offset().top });

}

 

Finally, you need to style the table of contents. I like the effect that I get with this:

#toc {

	background-color: white;

	max-width: 10em;

	border-radius: 1em;

	float: left;

	position: absolute;

	top: 20px;

	right: 10px;

	-moz-box-shadow:13px	13px	10px	#555;

	-webkit-box-shadow:5px 5px 5px #555;

	padding-top: 5px;

	padding-bottom: 5px;

	behavior:url(/content/pie.htc);
}
#toc
	li {

	list-style: none;

	padding-left: 1em;

	padding-right: 1em;

	line-height: 1.5em;
}

You can take this a step further by adding named anchor tags before headers or legends or similar tags that you might be interested in.

Posted on Friday, January 11, 2013 9:18 AM Stylish musings , jQuery | Back to top


Comments on this post: Easily Add a Table of Contents to Any Web Page with jQuery

comments powered by Disqus

Copyright © Nick Harrison | Powered by: GeeksWithBlogs.net | Join free