Skip to content

Instantly share code, notes, and snippets.

@mattattui
Created January 7, 2014 16:36
Show Gist options
  • Save mattattui/8302079 to your computer and use it in GitHub Desktop.
Save mattattui/8302079 to your computer and use it in GitHub Desktop.
Sample jquery theme-switcher
<?php
// This code shouldn't actually be *here*, obviously
$theme = filter_input(INPUT_POST, 'theme', FILTER_VALIDATE_REGEXP, [
'options' => [
'regexp' => '/^pink|blue|whatever$/',
],
]);
if ($theme) {
// Persist the theme somehow (just session here, but could be cookie or user profile)
$_SESSION['theme'] = $theme;
}
?>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Theme switcher sample</title>
<script src="//code.jquery.com/jquery-1.10.2.min.js" type="text/javascript"></script>
</head>
<body>
<ul class="switcher" data-update-url="/user/profile/settheme-or-whatever.php">
<li><a href="#" data-theme="blue">Blue</a></li>
<li><a href="#" data-theme="pink">Pink</a></li>
<li><a href="#" data-theme="whatever">Whatever</a></li>
</ul>
<div class="themed theme-whatever"><!-- Inject saved initial theme class here with PHP -->
<h2>My themed section</h2>
<p>Lorem ipsum dolor sit amet, <a href="#">consectetur</a> adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</div>
<script type="text/javascript">
$('.switcher').on('click', '[data-theme]', function (evnt) {
evnt.preventDefault(); // Relax, browser, I got this
// Change the theme - remove existing themes, add the selected one to any element with the .themed class
var themeclass = 'theme-' + $(this).data('theme');
$('.themed').removeClass('theme-blue theme-pink theme-whatever').addClass( themeclass );
// Update the server
$.ajax({
url: $('#switcher').data('update-url'),
data: { theme: $(this.data('theme'); )},
dataType: 'json',
type: 'POST',
error: function (resp, textStatus, errorThrown) {
alert('Unable to save theme change');
}
});
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment