public
Last active

Anchor-include Pattern

  • Download Gist
anchorinclude.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
/*
* anchor-include pattern for already-functional links that work as a client-side include
* Copyright 2011, Scott Jehl, scottjehl.com
* Dual licensed under the MIT
* Idea from Scott Gonzalez
* to use, place attributes on an already-functional anchor pointing to content
* that should either replace, or insert before or after that anchor
* after the page has loaded
* Replace: <a href="..." data-replace="articles/latest/fragment">Latest Articles</a>
* Before: <a href="..." data-before="articles/latest/fragment">Latest Articles</a>
* After: <a href="..." data-after="articles/latest/fragment">Latest Articles</a>
* Also, the data-threshold attr allows a min width for this to apply.
* On domready, you can use it like this:
$("[data-append],[data-replace],[data-after],[data-before]").ajaxInclude();
*/
(function( $ ){
$.fn.ajaxInclude = function( e ) {
return this.each(function() {
var el = $( this ),
target = el.data( "target" ),
targetEl = target && $( target ) || el,
threshold = screen.width > parseInt( el.data( "threshold" ) || 0 ),
methods = [ "append", "replace", "before", "after" ],
method,
url;
 
if ( threshold ) {
 
for( var ml = methods.length, i=0; i < ml; i++ ){
if( el.is( "[data-" + methods[ i ] + "]" ) ){
method = methods[ i ];
url = el.data( method );
}
}
 
if( method === "replace" ){
method += "With";
}
 
if( url && method ){
$.get( url, function( data ) {
var responseEl = $(data),
eTarget = method === "replaceWith" ? responseEl : el;
targetEl[ method ]( responseEl );
eTarget.trigger( "ajaxInclude", [eTarget, data] );
});
}
 
}
});
};
})( jQuery );

Would be cool to have these trigger on media queries so on smaller screens, you get a link but on desktop you could expand the link automatically.

Good idea. you could do something like...

if( window.screen.width > XXX ){  $("[data-replace]" ).anchorInclude()  }

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.