Jump to content

AJAX driven content and body classes


a-ok
 Share

Recommended Posts

Hi folks,

I'm building a fairly simple site using PW but I am also working with AJAX driven content (as noted by @ryan here: https://processwire.com/talk/topic/225-how-to-work-with-ajax-driven-content-in-processwire/) and everything works fine except for the change of body classes per page.

So, for example, in the head.inc I have the following:

<body class="<?php echo $page->name; ?>">

which is useful as it means I can create page specific styles etc. However, as the head and foot remain constant if an AJAX request is called using the following, for example:

<?php if(!$config->ajax) include('./head.inc'); ?>

the body class fails to update for obvious reasons.

Is there any way round this so the body class is updated per ajax call, if you know what I mean? This may be a global AJAX question and not a PW specific question but thought I would ask all the same.

Thanks,

R

Link to comment
Share on other sites

At best one doesn't even send rendered markup via ajax which would mean you could easily swap the class on the client. In your case, how about using json in a small version like so:

<script type="text/javascript">
  if(myconfig == undefined) var myconfig = { "title": <?php echo $page->title; ?> };
  else myconfig = { "title": <?php echo $page->title; ?> };
</script>

Inline it to your ajax response and use the infos by your javascript after the ajax request is done.

Link to comment
Share on other sites

You probably have the class name in the text of each item in the navigation, so why not use it?

With jQuery, written in the browser, and making lots of assumptions about your markup. but so you get an idea:

$('nav a').click(function () {
    // do your ajax thing
    // and then
    $('body').addClass($(this).text().toLowerCase());
});

or, in case you use the name of the page, or anything else instead of the text in the nav item, add it as title or even data-something attribute to the link in the nav and do instead:

    $('body').addClass($(this).attr('data-something'));
Link to comment
Share on other sites

Hi folks, thanks for all your replies. Here's how I did it.

$(document).on('pjax:end', function() {
    var bodyClass = $('meta[name=body-class]').attr('content');
    if (bodyClass !== undefined) { document.body.className = bodyClass; }
});

Then on every template which would be within the ajax/pjax container:

<meta name="body-class" content="<?php echo $page->name; ?>" />

Thanks,

R

  • Like 2
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...