Friday, December 5, 2014

Javascript: Create a dinamic table of contents

If you have a div with a lot of content (<div id="#content"> in this example) that is seperated by headers (h3 in this example), you can generate a list of the headers with links to them. Of course you will need jQuery for this :-)

(This was created by my colleagues Tibi & Katesz)


 <script type="text/javascript">  
      function setInnerLinks(containerID, elementClass){  
           $('#' + containerID).prepend("<ul id='" + containerID + "_links'></ul>");  
           var count = 0;  
           $('#' + containerID + ' ' + elementClass).each(function() {  
                $(this).attr('id',('' + elementClass + '_' + (++count)));  
                var titleText = $(this).text();  
                $('#' + containerID + '_links').append("<li><a href='#" + elementClass + '_' + count + "'>"+ titleText +"</a></li>");  
                //make it scroll  
                $('#' + containerID + '_links li a').last().click(function(e){  
                     e.preventDefault();  
                     var link = $(this);  
                     $('html,body').animate({ scrollTop: $($(link).attr("href")).offset().top }, (count * 200));  
                });  
           });  
      }  
      $(document).ready(function(){  
           setInnerLinks('content', 'h3');  
      });  
 </script>