1

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.

Ian Douglas
  • 97
  • 1
  • 1
  • 8

2 Answers2

1

I've looked at your URL and I think I can see the problem...

Try changing line 25 of the styleswitcher code from:

$('link[@rel*=style][title]')

To:

$('link[rel*=style][title]')

I think that the @ is no longer necessary with recent versions of jQuery and may be causing problems (I wrote the style switcher code but it was many years ago and jQuery has changed a lot since). Let me know when you've updated your URL and if necessary I'll update my copy of the script so other people don't run into the same problem...

I also notice that in your page I can't currently see the two stylesheets ("default" and "contrast") that you were trying to add. Check that you are correctly adding them to the page as well...

vitch
  • 3,215
  • 3
  • 25
  • 26
  • Thank you, Vitch. I changed it, and also added my default css to functions.php with the name "white" (see my original post above). I changed the header.php to reflect that. Right now, pressing "Focus mode" which is my toggle, does nothing. But it don't jump the page around like it did, which is a good thing. – Ian Douglas Aug 07 '14 at 10:12
  • Tried adding ' ' to page.php, single.php, index.php, and _page-cover-wrap.php (which is where the "Focus mode" toggle is). Makes no difference. – Ian Douglas Aug 07 '14 at 10:25
  • I can see the code has been output twice to your page now! If you view source and find " – vitch Aug 07 '14 at 11:09
  • Having ' ' anywhere produces a Too Many Redirects error. I've tried several combinations. To clarify: a) It should be in header.php, in the head tag, right? b) It should also be somewhere on my page. I've tried putting in single.php, page.php, and _post-cover-wrap.php, which is where "Focus mode" appears, the supposed toggle. Since changing the link refs to stylesheet and alternate stylesheet, I get the Redirects error. – Ian Douglas Aug 07 '14 at 11:37
  • Do I need the code in index.php (see my original question above), while also calling the script in header.php? – Ian Douglas Aug 07 '14 at 11:39
  • Vitch, I found that you don't need to put the Link rels code in single.php for the switcher to work. Header.php is sufficient. I just needed absolute URLs. It now switches perfectly, and the cookie works. I just have one "ERR_TOO_MANY_REDIRECTS" to fix, which is slowing the site to a crawl – Ian Douglas Aug 07 '14 at 16:04
  • For the "ERR_TOO_MANY_REDIRECTS" I just looked in the web inspector and it looks like you are trying to load a stylesheet at http://thiscouldbeparadise.org/wp-content/themes/ink-child/contrast.css?ver=3.9.2 which doesn't exist. And there is probably something wrong with your 404 error page setup in wordpress. I would suggest asking another question about these issues though as it's not related to the initial question. – vitch Aug 07 '14 at 16:44
  • Thank you, Vitch, for all your help. It's working now. On the ink-child/contrast.css file, I just created it. Strangely, there is nowhere in my theme files where any reference to it occurs. I searched. I also searched all plugins, and the database. So I can't imagine how that file is being loaded. It still shows up in Source in Chrome and Firefox, even after purging page caches. Anyway, the switcher works and the page loads normally, with only a minor error from Jetpack. Thanks again – Ian Douglas Aug 07 '14 at 17:49
0

you have a mistake in wp_enqueue scripts

wp_enqueue_script('stylesheetToggle.js');

should be

wp_enqueue_script('stylesheetToggle');

also the file you are loading needs to be in no conflict jquery, the simplest way of doing this is the replace each $ symbol with the word jQuery in your files (the 2 files you are enqueuing).

Also check paths to your theme are correct etc.

Also check you js files with jsfiddle it has a handy hint button (no php vars in the js code for this to work).

Post back if your still having problems.

David
  • 5,897
  • 3
  • 24
  • 43
  • Thanks David. I changed enqueue. I tried to implement no conflict, but I think I'm not doing it correctly. One has to literally find/replace $ with jQuery in every instance? Including the first line? The .js file is here: http://pastebin.com/wwE8674i The other file I'm enqueuing is a .css file. I checked paths. It looks okay to me. I tried to get a jsfiddle to work, but failed. It's here: http://jsfiddle.net/immanence/F9HLk/1/ I noticed in the second function I'm adding to the functions.php I had had wp_register_script. I changed this to wp_register_style. Similarly, wp_enqueue_style – Ian Douglas Aug 06 '14 at 11:52
  • no its ok to do it the way your file has it also. Check the console and start working through the errors. Also get_template_directory_uri() dosent take parameters so what you need is get_template_directory_uri().'/yourfile.php' – David Aug 06 '14 at 12:07
  • Thank you, David. I edited my original question to reflect the errors now corrected. So above is currently the code I'm using, and where. I added / to the href in my header.php, which seemed to eliminate the Too Many Redirects errors. Right now, there are no console errors. But the switcher doesn't work. I think because I haven't called it. It's unclear to me, in fact, how to call it, and where. So, progress, but not resolution yet. Notice I'm not including the script in the header. This was producing the redirects. Also, now, the custom css style is what is loading on the page, not my default – Ian Douglas Aug 06 '14 at 13:03
  • remove the – David Aug 06 '14 at 16:38
  • I added the script (see my original post above) in header.php. I hope correctly. On the code, I don't know what to do with it. Where should it go? Should I wrap it with: 'jQuery(document).ready(function($) { //code. });' – Ian Douglas Aug 06 '14 at 18:09
  • try moving it below the header in script tags. Also do the same for no.conflict either change the $ to jQuery or add the $ in the function tags and append with (jQuery). The $(function is a method of document ready so thats already there, but if you are calling it before jQuery is loaded it dosent know itself. – David Aug 06 '14 at 21:49
  • I edited my question to include that script. I don't know if I'm doing this correctly. Anyway, I tried adding to the header.php. In the head and the body. Neither makes any difference. – Ian Douglas Aug 07 '14 at 07:29
  • In case it helps, I added the URL to the page in my main question, down at the bottom – Ian Douglas Aug 07 '14 at 08:42
  • get rid of $.noConflict(); – David Aug 07 '14 at 08:46
  • Done. Right now, this code is between /head and body. I get errors in Chrome's Console that I don't know the meaning of at all – Ian Douglas Aug 07 '14 at 09:04
  • check your urls in the stylesheet links, prob better to construct a absolute url using get_stylesheet_directory_uri(); or similiar. – David Aug 07 '14 at 15:21
  • That works, David! Thank you so much! I changed all values in header.php to absolute URLs, but not in functions.php, as absolute value seemed to create additional "ERR_TOO_MANY_REDIRECTS" in the Console. I'm still getting one "Failed to load resource: net::ERR_TOO_MANY_REDIRECTS" which I'm unsure how to get rid of. It seemed to first appear when I set the Link rel to 'stylesheet' and 'alternate stylesheet' as suggested by Vitch above (who wrote the HTML switcher). But this is necessary for the .js code. The error slows the site to a crawl. It's the last error, but an important one – Ian Douglas Aug 07 '14 at 16:03
  • All working now. Thanks so much for all your help. I'll try to mark both responses (yours and Vitch's) as answers, as both were important – Ian Douglas Aug 07 '14 at 17:51
  • well done. Maybe mark Vitches if he would be kind enough to update a link to his code and include a wp friendly template call. Prob help more people that way. – David Aug 07 '14 at 17:59