Created
November 11, 2016 15:31
-
-
Save Camwyn/9b9260453c351608cbe1ac288cf4c395 to your computer and use it in GitHub Desktop.
"Stacked" items using scroll-to-fixed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Sticky / scroll-to-fixed elements | |
| */ | |
| ( function( window, $ ) { | |
| 'use strict'; | |
| // This array contains all the elements we want to "stick" You can add | |
| // another in, but the order matters! Each gets margin-top that includes | |
| // the height of the previous items. | |
| var eleList = [ | |
| $( document.getElementById( 'sticky-search-js' ) ), | |
| $( document.getElementById( 'page-header-alert-js' ) ), | |
| $( document.getElementById( 'page-utilities-js' ) ), | |
| ]; | |
| // This is the function that calculates the margin top for each element | |
| function calcMT( i ) { | |
| var marginTop = $( document.getElementById( 'wpadminbar' ) ).outerHeight(); | |
| // If you add an element to the list that shouldn't add to the marginTop, | |
| // Put a check for it in here - remember that it will get a marginTop | |
| // that includes all the elements that come before! | |
| while (0 < i) { | |
| i--; | |
| marginTop += eleList[i].outerHeight(); | |
| } | |
| return marginTop; | |
| } | |
| // This is the function that does the "heavy-lifting". | |
| function stickit() { | |
| eleList.forEach( function( $ele, index ){ | |
| $ele.scrollToFixed({ | |
| marginTop: function(){ | |
| return calcMT(index); | |
| }, | |
| }); | |
| }); | |
| } | |
| // Run through the elements and stick each one if present. | |
| // Their order in the array will ensure that they all get the correct "top" | |
| $( document ).ready( function() { | |
| stickit(); | |
| } ); | |
| } )( this, jQuery ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment