Last active
October 21, 2021 11:06
-
-
Save Clorith/a701464e69e65ac0e959 to your computer and use it in GitHub Desktop.
jQuery script for loading more content over ajax.
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
/** | |
* Load more content over ajax in a nice manner | |
* | |
* This script utilizes Font Awesome to give proper visual feedback | |
* while the new content is being fetched and loaded | |
* | |
* Usage: | |
* - Attach the class 'load-more-content' to any a tag in the DOM | |
* - Give this object a data attribute of data-content-area which indicates | |
* what part of the site is to be loaded in | |
* | |
* Example: | |
* <a href="www.site.com/list/page/2" class="load-more-content" data-content-area="#main">This is a link</a> | |
* | |
* The script will now look for any object with the id "main" on page 2 and | |
* append this to the id "main" on the current page. | |
* It will also look for an instance of it self o nthe next page to update the load more address. | |
* | |
* Gracefully degrades if JavaScript should be disabled as the link is still a link to the next page | |
*/ | |
jQuery(document).ready(function ($) { | |
$("body").on( 'click', '.load-more-content', function (e) { | |
e.preventDefault(); | |
var $request = $(this), | |
label = $(this).html(); | |
$(this).html('<i class="fa fa-spinner fa-spin"></i>'); | |
$.post( | |
$request.attr('href'), | |
function (next_page) { | |
var content = $($request.data('content-area'), next_page).html(); | |
var $more = $("[data-content-area='" + $request.data('content-area') + "']", next_page); | |
$($request.data('content-area')).append( content ); | |
$request.html( label ); | |
$request.attr('href', $more.attr('href')); | |
} | |
); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment