Auto linker for when you're splitting one page into many

by timmah

JavaScript

// This script checks and auto-populates fragment links based on which page they lead to.
// Just add the wrapper '<div class="pagewrap" id="pgX">' with each ID(pgX) a new page number, and 
// replace the $pages objects below with your page node IDs

// Replace each page number with the desired node IDs. Add as many pages as required
var $pages = {
	pg1: '492259',
	pg2: '492264',
	pg3: '492260',
	pg4: '492261',
	pg5: '492265',
	pg6: '492266',
	pg7: '492267',
	pg8: '492326',
	pg9: '492325'
}

var counter = 0;

// Target all fragment links via CSS
$('a[href^="#"]').each(function()	{

	// Give the number of the link in question
	counter++;
	
	var $this = $(this),
			$frag = $this.attr('href').split('#')[1],
			$parent = $(this).parents('.pagewrap').attr('id');

	// Check for any element with that ID within that section (page)
	if ($('#' + $parent + ' #' + $frag).length !== 0) {
  
//		console.log('Target for: ' + $frag + ' found on this page, no action required');
	
  } else {

		console.log('Target not found for: ' + counter + ': ' + $frag);

		var $target = $('#' + $frag),
				$wrapper = $target.parents('.pagewrap').attr('id');
			
      // Update the link to point to the appropriate node, then add the fragment on the end. 
      // Note the use of bracket notation to access the object key with a variable. Dot notation won't work. 
      $this.attr('href', '/node/' + $pages[$wrapper] + '#' + $frag);
	}
});