Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Apr 26th, 2012  |  syntax: None  |  size: 1.80 KB  |  hits: 14  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. List with elements that attaches the top magically when scrolling
  2. <h3>Category 1</h3>
  3. <ul>
  4.     <li>blabla</li>
  5.     <li>blabla</li>
  6.     etc...
  7. </ul>
  8. <h3>Category 2</h3>
  9. <ul>
  10.     <li>blabla</li>
  11.     <li>blabla</li>
  12.     etc...
  13. </ul>
  14. <h3>Category 3</h3>
  15.     etc...
  16.        
  17. $('#scroller').scroll(function () {
  18.     var positions = $('h3', this).map(function() {
  19.             return {
  20.                 top: $(this).position().top,
  21.                 el: this
  22.             };
  23.         }).get();
  24.  
  25.     //Go backwards through the array and pick the first negative (smallest) value
  26.     for(var i = positions.length - 1; i >= 0; i--) {
  27.         if(positions[i].top < 0) {
  28.            $('#header').text($(positions[i].el).text());
  29.            return;
  30.         }
  31.     }
  32. });
  33.        
  34. $('#scroller').scroll(function () {
  35.     var category = '';
  36.  
  37.     $($('h3', this).get().reverse()).each(function () {
  38.         if($(this).position().top < 0) {
  39.             category = $(this).text();
  40.             return false;
  41.         }
  42.     });
  43.  
  44.    $('#header').text(category);
  45. });
  46.        
  47. <div style="position:fixed;right:0px;" id="place">Category 1</div>
  48.  
  49. <h3>Category 1</h3>
  50. <ul>
  51.     <li>blabla</li>
  52.     <li>blabla</li>
  53.     etc...
  54. </ul>
  55. <h3>Category 2</h3>
  56. <ul>
  57.     <li>blabla</li>
  58.     <li>blabla</li>
  59.     etc...
  60. </ul>
  61. <h3>Category 3</h3>
  62. <ul>
  63.     <li>blabla</li>
  64.     <li>blabla</li>
  65.     etc...
  66. </ul>
  67.  
  68.  
  69. <script>
  70.  
  71. var headers = document.getElementsByTagName("h3");
  72.  
  73. var place = document.getElementById("place");
  74.  
  75. addEventListener("scroll", function(e) {
  76.  
  77.     var scroll = document.body.scrollTop;
  78.     var foundHeader = false;
  79.  
  80.     for(var i = headers.length-1; i >= 0; i--) {
  81.  
  82.         var h = headers[i];
  83.         var top = h.offsetTop;
  84.  
  85.  
  86.         if(!foundHeader && scroll+50 > top) {
  87.             place.innerHTML = h.innerHTML;
  88.             foundHeader = true;
  89.         }
  90.  
  91.  
  92.  
  93.  
  94.     }
  95.  
  96. }, true);
  97.  
  98. </script>