Creating an AJAX populated navigation in WordPress, without the API

By North Street, A Creative Studio

For Bartaco, when you click on “locations” in the main navigation, a full-screen modal takeover appears:

Screen Shot 2016-02-01 at 1.58.26 PM

Screen Shot 2016-02-01 at 1.57.34 PM

This could be handled by simply always having this modal hidden in the header, then showing it when clicking on “location”. However, that means that this query would run on every single page load.

The solution is to to use AJAX, coupled with special pages to output the required query.

The content from that above model, is actually being pulled in on this page:

Screen Shot 2016-02-01 at 2.15.18 PM

This page is not linked on the site, nor is it meant to be accessible by the user. If Google finds it in a sitemap, it’s great for SEO though.

This page has a div called “.content”, which using the same exactly DOM structure as fond on the modal view — It’s simply styled differently.

So here’s how it works:

  1. On click, we grab the href and check if we’ve click on the “locations” navigation item.
  2. If so, we disable the click, and instead fade in the modal.
  3. At this point, the modal is styled to be empty with a loading graphic.
  4. Next we simply use the jQuery .load() method, and grab the “/locations/” page, and the contents of the “.content” div.
  5. Then we add a class to the modal, which displays the new styles.

Relevant JS below (main.js)

	/* Detect /locations/ and open up modal instead. 
	Actual /locations/ page simply goes back to home */ 
	$('a').click(function(e){ 
		var url = $(this).attr('href');

		if (url.indexOf("/locations/") >= 0) 
		{
			$('.select-state').fadeIn();

			// Only want to load up state select once 
			if (!$('body').hasClass('select-state-loaded')) {
				$('.select-state .pop-out-inner').load( "/locations/ .contents");
			}
			e.preventDefault();
			$('body').addClass('select-state-loaded');
		}
	});

 

 

About north street

We engineer the thoughtful transformation of great organizations. Our proven process helps us understand what your competitors are doing right — and wrong. Want to learn more? Let’s chat.

More Notes

Team Spotlight: Matt Potter, Web Designer

Postcards from Puerto Rico: North Street Retreat ’22

We’re Hiring: Marketing Coordinator