I'm trying to implement a simple Toggle based style switcher in Wordpress. The solution was originally written for HTML. It can be found here.
The necessary .js files can be found there. Look at Vitch's comments below to correct one error in the stylesheetToggle.js file.
What this provides is a simple text link that I can put in my template that toggles between two stylesheets, with no page refresh, and is linked with a cookie that remembers the user's choice if they go elsewhere in the site.
This is what I have got so far (sorry, I'm cobbling this together from what I can learn reading scores of attempts to create a style switcher).
All files are on root of my theme folder, for simplicity sake.
I added this to my functions.php:
function wpb_adding_scripts() {
wp_register_script('stylesheetToggle', get_template_directory_uri() . '/stylesheetToggle.js', array('jquery'),'1.1', false);
wp_enqueue_script('stylesheetToggle');
}
add_action( 'wp_enqueue_scripts', 'wpb_adding_scripts' );
function wpb_adding_styles() {
wp_register_style('contrast', get_stylesheet_directory_uri() . '/contrast.css');
wp_enqueue_style('contrast');
wp_register_style('white', get_stylesheet_directory_uri() . '/style.css');
wp_enqueue_style('white');
}
add_action( 'wp_enqueue_scripts', 'wpb_adding_styles' );
Then in my index.php I added (at the top, above get_header(); ?>):
<?php wp_enqueue_script("stylesheetToggle"); ?>
In my header.php I added:
<link rel="stylesheet" type="text/css" href=" ... /style.css" title="white">
<link rel="alternate stylesheet" type="text/css" href=" ... /contrast.css" title="contrast">
<?php wp_enqueue_script("stylesheetToggle"); ?>
NOTE: URLs to stylesheets need to be absolute paths.
This also goes in header.php, between the end of the "head" and start of the "body":
<script>
jQuery.noConflict();
jQuery(document).ready(function($) {
$(function()
{
// Call stylesheet init so that all stylesheet changing functions
// will work.
$.stylesheetInit();
// This code loops through the stylesheets when you click the link with
// an ID of "toggler" below.
$('#toggler').bind(
'click',
function(e)
{
$.stylesheetToggle();
return false;
}
);
// When one of the styleswitch links is clicked then switch the stylesheet to
// the one matching the value of that links rel attribute.
$('.styleswitch').bind(
'click',
function(e)
{
$.stylesheetSwitch(this.getAttribute('rel'));
return false;
}
);
}
);
});
</script>
In my relevant template file, I added:
<a href="#" id="toggler">Focus mode</a>
RESULT: This works now, thanks to Vitch and David.
Page URL: http://thiscouldbeparadise.org/change/
"Focus mode" is supposed to toggle the available stylesheets.