orioltf
8/6/2013 - 3:24 PM

#JQUERY #WebEnhancer: Get Github help answers via AJAX accordion like - no page jump. Add this code as Chrome snippet and run it when browsi

#JQUERY #WebEnhancer: Get Github help answers via AJAX accordion like - no page jump. Add this code as Chrome snippet and run it when browsing github help

;(function($, window, document, undefined) {
  var $questions = $('ul.chevron'),
		answerClass = 'answer',
		answerSelector = '.'+answerClass,
		questionSelector = 'a.km-article-link',
		questionWrapperSelector = '.article',
		loadingIcon = 'https://github.global.ssl.fastly.net/images/spinners/octocat-spinner-32.gif',
		// vars to fix css definitions
		sheet = document.styleSheets[0],
		rules = typeof(sheet) != 'undefined' ? ('cssRules' in sheet? sheet.cssRules : sheet.rules) : {}, // IE compatibility
		questionLinkSelectors = ['ul.chevron li a','div#common-issues ul li a'],
		questionLinkSelectorsPatched = ['ul.chevron > li > a','div#common-issues ul > li > a'];
	
	$('<img />')
		.attr({
			'src':loadingIcon,
			'width':'16px',
			'height':'16px',
			'id':answerClass+'Loader'
		})
		.appendTo('body').css('display','none');
	
	if ($questions.length) {
		$questions.find('li')
			.append('<div class="'+answerClass+'" />')
			.find(answerSelector)
				.css({
					'padding':'10px',
					'background-color':'#f5f5f5',
					'margin':'0.65em 0 1.5em 0.65em',
					'display':'none'
				});
		$questions.find(questionSelector).click(function(e){
			e.preventDefault();
			var linkRef = $(this).attr('href'),
				$answer = $(this).closest(questionWrapperSelector).find(answerSelector),
				$openAnswer = $(this).closest(questionWrapperSelector).siblings().find(answerSelector).filter(':visible');
			
			// If the answer has not been yet loaded
			if( $answer.html().length == 0 ) {
				$('#'+answerClass+'Loader').appendTo($(this)).show();
				$answer.load(linkRef+' #content-wrapper > .site > .article > .article-body', function(){
					$(this).slideDown(function(){
						$('#'+answerClass+'Loader').hide();
					});
				});
			} else { // The answer was previously loaded
				$answer.slideToggle();
			}
			$openAnswer.slideUp();
		});
	}
	
	
	// Fix links styles, so that the links style definition does not affect the ajax loaded content
	for(i=0;i<rules.length;i++) {
		for(j=0;j<questionLinkSelectors.length;j++) {
			if(rules[i].selectorText == questionLinkSelectors[j]) {
				rules[i].selectorText = questionLinkSelectorsPatched[j];
			}
		}
	}

})(jQuery, window, document);