Posted on Leave a comment

Toggle WordPress Background Image for Readability


Why and How We Toggle the Background

For reasons related to the origin of our site we want to keep our background image although for readability it is less than ideal. So the question was, how do we enable the user to effortlessly hide the background image if they wish to improve the contrast of the page?

As our site uses WooCommerce, for small mobile screens we wanted to have our ‘Contrast’ button in the handheld footer menu.

While the button would say ‘Contrast’, we thought a, not to be missed, tooltip was necessary. Also a tooltip that would, in some way, cope with the absence of hover on touch screens was desirable.

Then it seemed that once the background image was hidden, the new state should apply to all newly opened tabs. This was achieved through the use of a cookie. Indeed, the background image state would apply consistently in the browser until the cookie expired after a day.

How we implemented each of the above goals is described in the following sections.

There’s quite a lot of JavaScript code to follow in this. If you’d like to see the completed code this can be done using the Chrome Developer Tools. Look at the ‘Sources’ tab and find the file ‘https://www.datastream.world/wp-content/uploads/siteground-optimizer-assets/custom-js.min.js’. This is a minified file, however, there is a pretty-print icon ‘{ }’ in the footer of the code window that allows you to see the formatted code.

Steps for a Floating ‘Contrast’ Button

  1. Guided by how to put your own feedback style twitter badge, however, not intending to use an image in the button, we added the following to the style.css file in our child theme.
    #contrast_button {
          position: fixed;
          z-index: 99999;
          right: 20px;
          top: 100px;
    }
    For the button to be mouse sensitive we found we needed a large z-index. The value of 99999 is arbitrary and effective. (Our effort to find the highest z-index in use in the stacking context was disappointingly fruitless.)

    We also copied header.php to our child theme and included, as a new <div> after #content, the following:
    <div id="contrast_button" class="a_contrast">
          <a id="a_contrast" href="javascript:void(0);"
               title="Toggle background image.">Contrast</a>
    </div>

    We don’t want the anchor click to take us anywhere, so the href we’ve used is explained in “Is an empty href valid?“.

  2. However, so far the anchor does not look like a button. So we added this style.css in our child theme:

    /* make the link look like a button */
    #contrast_button{
          border: 1px solid black;
          border-radius: 5px;
          padding: 0px 3px;
          background-color: #E3E3E3;
    }

    #contrast_button:hover{
          background-color: #E0FFFF;
    }

  3. When we click the button we want to hide the background image. An inspection of page source or the article How To Properly Add Background Images To Your WordPress Site tells us that we need to remove the css for the class custom-background and replace it with other css that we’ve called custom-contrast. So we added this css to our child theme style.css:
    /* Toggled values to replace custom-background */
    .custom-contrast{
          background-image:none;
          background-color: #E3E3E3;
    }
    Then, following the up-voted code in Changing background color in wordpress with a button so that these values toggle when we click the button, we added the following to our custom.js file (we’re using the theme-customisations plugin):
    jQuery(function($){
          $("#contrast_button").on("click", function(e){
               e.preventDefault();
               $('body').toggleClass(
                    'custom-background custom-contrast');
          });
    });

    To allow us to use the $ shortcut we have followed Using ‘$’ instead of ‘jQuery’ in WordPress and also the recommended jQuery syntax.

And that’s all that’s necessary for the floating button.

Handheld Footer Bar ‘Contrast’ Button

  1. Guided by Customize links in the handheld footer bar we added the following to our functions.php:
    /*
    * Add a link in the handheld footer bar
    */
    add_filter( 'storefront_handheld_footer_bar_links',
         'add_contrast_link' );
    function add_contrast_link( $links ) {
         $new_links = array(
               'contrast' => array(
                    'priority' => 10,
                    'callback' => 'contrast_link',
               ),
         );
         $links = array_merge( $links, $new_links );
         return $links;
    }
    function contrast_link() {
         echo '<a id="contrast_bar_button"
              href="javascript:void(0);"
              title="Tap to toggle background image.">'
                   . __( 'Contrast' ) . '</a>';
    }
    This is enough to add the link in the footer bar, but we do not yet have an icon.  So, additionally we need to add to style.css:
    .storefront-handheld-footer-bar ul li.contrast > a:before {
          content: "f042";
    }

  2. For the footer bar button to do the same action as the contrast button, we just need to add its selector to the line:
    $("#contrast_button").on("click",function(e){
    to become:
    $("#contrast_button, #contrast_bar_button").on("click", function(e){

  3. And lastly, we needed to turn off the ‘Contrast’ button in the page body, so we added this to style.css:
    /* don't display the contrust button on handheld */
    @media only screen and (max-width:768px){
          #a_contrast, .a_contrast {
               display: none !important;
          }
    }

And that’s all that’s necessary for the footer bar button.

Adding a Big Tooltip to the ‘Contrast’ Button

  1. For the tooltip we followed the post Responsive and Mobile-Friendly Tooltip.  So firstly we added the attribute rel="tooltip" to our anchor elements (id’s a_contrast and contrast_bar_button) above.

    Then, we wanted the tooltip:

    1. to automatically disappear after 3 seconds.
    2. to show itself on page load, so attention is drawn to the button.
  2. So we included the CSS as shown in the post in style.css, except for small variations as shown here:
    #tooltip
    {
          text-align: center;
          color: #fff;
          background: #0000FF;
          position: absolute;
          z-index: 99999;
          padding: 15px;
          border-radius: 5px;
    }
    Here we’ve chosen a different background colour, we needed to increase the z-index and we choose rounded corners.
  3. We included the JavaScript largely as shown, but with the following changes for 1a and 1b above and since we already have document ready handling, then c below:
    1.  We added, at the end of the init_tooltip function, a timeout, thus:
      window.setTimeout(remove_tooltip, 3000);
        
    2. The changes for the on page load tooltip display are fivefold:
      1. we named the function bound to the variable targets using a function expression, thus:
        var show_tip = function()
          
      2. So now we have (noting that .bind is, sort of, deprecated), to keep the original functionality:
        targets.on( 'mouseenter', show_tip);
          
      3. Then we added after the above line of code:
        show_tip();
        in order to show the tooltip on page load, however, there is a problem, because the object this is the window object and not the button clicked.
      4. So how to select the button?  Well the buttons are held in the variable targets and in our case only one is visible, either the floating button or the footer bar button.  So which is visible?  Guided by How to check an element is visible or not using jQuery this is how we found out:
        var vis;
        $(targets).each(function (index, element){
              if ($(element).is(":visible")){
                   vis = element;
                   return false;
              };
        });
        So now we know which button element is visible and thus the button we should tooltip when this is the window object.  
      5. This is how we test if this is the window object, so accordingly we evaluate:
        this != null && this === this.window
        Hence we replaced:
        target  = $(this);
        with:
        target = $(
             (this != null && this === this.window)? vis : this
        );
         
    3. We removed the construct:
      $( function() { < // code we keep >  });
      since we already have a document ready construct:
      jQuery( function($) {  // Our toggleClass code  });
      so we included all our code within this later construct.

And that’s all that’s needed for the footer bar ‘contrast’ button.

Using a Cookie to Know the ‘Contrast’ State

  1. Knowing nothing of the subject, we first read How to Set, Get, and Delete WordPress Cookies (like a Pro).  We also read the PHP documentation on setcookie, noting the protocol restrictions regarding HTTP headers.
  2. Our cookie was generally to have a value of ‘low’ or ‘high’ corresponding to the contrast states of, background image showing, and no background image, respectively.  However, we introduced an initial state of ‘init’ which allowed us to show our tooltip for longer when the cookie was created.

  3. Update 22 May 2020.  With the buzz around Chrome’s cookie SameSite policy rollback in the COVID-19 pandemic, we decided now was the time to get SameSite as right as possible.   Our current PHP version is 7.3 and is relevant to our solution as discussed.  Getting it right was not easy as there are suggestions which did not work for us.  On reading Secure better your website with SameSite cookies we used the header function to set the cookie where formerly we had used the setcookie function.  So to create our cookie we added the following to theme functions.php:
    /*
    * Contrast cookie
    */

    function set_contrast_cookie() {
          // Check if cookie is already set
          if(!isset($_COOKIE['contrast_state'])) {
               // Set the cookie, expires in 1 day
               $expire = date('D, d M Y H:i:s', time() + 60*60*24); // one day from now
               header("Set-cookie: contrast_state=init; expires=$expire; path=/; SameSite=Lax");
          }
    }
    add_action('init', 'set_contrast_cookie');
  4. Once the cookie has been created, all our other cookie handling can be done by the browser with JavaScript.

    How should cookies be handled JavaScript?  We found How do i set/unset a cookie with jQuery which pointed us to js-cookie.

  5. To remove the background image if the cookie value is ‘high’, we need to act as if the ‘contrast’ button had been clicked.  So we added the following to custom.js:
    var contrast;
    // Page load set contrast high if necessary
    contrast = Cookies.get("contrast_state");
    if (contrast == 'high') {
         $('body').toggleClass('custom-background custom-contrast');
    }
  6. Now we needed to set the cookie when the ‘contrast’ button is clicked, so we added to custom.js in the function for the contrast button .on(‘click’:
    contrast = Cookies.get("contrast_state");
    Cookies.set('contrast_state',
         (contrast == 'low') ? 'high' : 'low',
         {expires: 1, path: '/', sameSite: 'lax'});

  7. We decided that we only wanted the tooltip to show without focus being on the ‘contrast’ button on the occasion when the cookie was created.  We thought that for it to appear on every page load might be irritating.  So we modified the show_tip(); statement to be:
    contrast = Cookies.get("contrast_state");
    if (contrast == 'init') {
         show_tip();
         Cookies.set('contrast_state', 'low',
              {expires: 1, path: '/', sameSite: 'lax'});
    }
  8. As mentioned above, we wanted the tooltip to show for longer on the initial page load when the cookie is created.  It’s now the case that the page load show_tip() is only done when the cookie value is ‘init’, that is only once before the cookie expires.  So we made some changes to the custom.js code.  In place of :
    var show_tip = function()
    {
         target = $((this != null && this === this.window)? vis : this);
    we now have:
    var show_for;
    var is_window;
    var show_tip = function()
    {
          is_window = (this != null && this === this.window);
          show_for = is_window ? 6000 : 3000;
          target = $(is_window ? vis : this);

And that’s all that’s needed for the cookie to know the contrast state.

Just a reminder, if you want to see all the JavaScript code, we explain how in the last paragraph of the first section ‘Why and How …’.

Posted on Leave a comment

My experience with Book Setup

I have set up two of my seven book titles to sell on Data Stream World.
After a simple log in set up, the site remembers me without having to type in details every time.
Very user friendly and easy for authors to follow the clear steps.
Easy to navigate between folders to check on what was written elsewhere,
Note that the first ‘alternative text’ box needs to describe the image with detail as to a blind person.
Pretty excited to be a part of this new system.

Posted on Leave a comment

The Cheeky Possum Grammar Notes


This Publisher’s Grammar Notes and References for Punctuation and Capitalization

Grammar: Punctuation and Capitalization
Grammar: Punctuation and Capitalization

In text editing for grammar we aim to be both consistent and only to change the author’s text where it seems necessary to avoid a glaring error.  In consequence, we keep as close as possible to the author’s work.  The Cheeky Possum text rhymes, so we have looked for grammar practices acceptable in poetry, which offer greater latitude than prose.

We hope these notes are useful to encourage the exploration of writing style and rules. Text editing … ugh!

Run-on Sentences, Comma Faults, …

Arguments can be mounted that the opening sentence of The Cheeky Possum should be multiple sentences, but we find it a great introduction to Peter and only when he’s given us his substance, do we stop and digest it.  Before coming to this conclusion, a number of articles published on the web were considered:

Capitalization in Poetry and ‘ise’ or ‘ize’

On capitalization of the first word of a line in poetry, as exhibited in The Cheeky Possum, we cite Alberto Rios writing on the subject.  Further, on our spelling of the word ‘capitalization’ in British and Australian English, we cite The Conversation article on the use of ‘ise’ and ‘ize’.

Should there be a Comma before a Quote?

Should there always be a comma before quotes? Not necessarily according to the Sesquiotica blog.  Apart from stand-alone, speech quoted sentences in The Cheeky Possum, all other speech can be viewed as anecdotal, broad-view description.

Capital Letter for a Quote in a Sentence?

The Grammar Monster says, “There is a lot of leniency on the use of capital letters for quotations embedded in sentences.  So we’ve allowed: He said ”hey now, this is proof, there’s hippos landing on my head!”.  The rendering on the page gives the utterance a dreamy quality as of someone suddenly awoken.

Said but not Spoken, No Quotation Marks?

There is an example of something described as, said, that is without quotation marks, that we have allowed.  Its usage is immediate and climatic, and is the thought that Bridgette has, namely: look up there; it’s a possum on a wire. This we take not to be an utterance, but her reaction to the situation.  To support this contention, we note that quoted dialogue follows this reaction.

Posted on Leave a comment

She’s a very tidy teenager

We’re nearing the end of The Cheeky Possum and it’s time to reflect on what we’ve seen and heard. Of course, within the story, the characters too are reflecting and drawing their own conclusions. Here we’re touching on an aspect of the magic of reading to your children. We are nurturing their intellectual development in many ways.

So we have the story, the reader and the listeners. With a picture book the listeners may also be looking and thinking about the illustrations. One looker and thinker, Aria says, of the illustration of Bridgette tucked up inside her bed, “She’s a very tidy teenager!”.

Posted on Leave a comment

Let’s Hear Your Ideas

A cactus flower
Too briefly beautiful

As Bex has suggested, this is an area for general comments. I’m on a learning curve, never having set up this kind of website before. I’ll try to respond quickly to your suggestions, but I may need to do some research on occasion.

I have now given Bex a role on the website so she can set up new topics like this one. If any of the Mothers’ Group would like similar, please send me an email. Anyone can post a comment (comments are moderated).

Posted on 2 Comments

Avery and Aria spot the kangaroo

Kangaroo in the moonlight
Kangaroo in the moonlight

It’s storytime and the lights are low.  We’re reading a pre-publication mockup of The Cheeky Possum, a real favourite with Avery.  We’re in cheeky possum world, so most of the illustrations are moonlit.  This is Peter, the cheeky possum’s favourite playground. A world of shadow and revelation, where the girls notice for the first time there is, in the picture, a kangaroo hopping.  Thank you to Derek Dadswell for the wonderful mood and graphic presentation of these illustrations.