Jump to content

Javascript - custom theme toggle (ie light/dark mode)

Go to solution Solved by MayaViolet,

Recommended Posts

Posted (edited)

Site URL: https://bywater-collective.squarespace.com/

Hi all - I am trying to use Jquery in order to give the ability for visitors to choose between a specific color theme on my client's 7.0 website. I have seen a number of tutorials walking through light vs dark mode, however I am trying to accomplish the following :

  1. Have three separate "color themes," that alter the index-page background color, and h1 font-color
  2. Depending on the "color theme" that is selected, have the logo image source, and photo image source within our mega-menu change accordingly. 

Here is an example of a website that displays the ability to toggle between "themes," and I've attached mockup examples of each "style". You can find my client site here, I appreciate any help and direction!

Menu - A.png

Menu - B.png

Menu - C.png

Edited by MayaViolet
  • 2 weeks later...
Posted

@MayaVioletTysm for sharing!! Do you mind sharing how you achieved this on Squarespace? I looked through the tutorial you linked and I'm a little stuck as to where to copy+paste the codes.

Posted
5 hours ago, xoxngo said:

@MayaVioletTysm for sharing!! Do you mind sharing how you achieved this on Squarespace? I looked through the tutorial you linked and I'm a little stuck as to where to copy+paste the codes.

Hi @xoxngo - you'll want to add the CSS to your custom CSS section, the javascript to your Header Code Injection, and then the toggle code will need to be applied as html via a codeblock on the page/area you'd like to apply the mode toggle section. Having a baseline understanding of these languages definitely helps - it's also helpful to take a look at the codepens included in the tutorial, and see how they broke down the html, CSS and javascript sections! Hope that helps 🙂

  • 8 months later...
Posted (edited)

Hi MayaViolet,

👋 I'm the developer of the Automatic dark mode plugin for Squarespace. Will try to push you in the right direction.

To make the dark mode plugin, I've spent 3+ months solving this problem. My plugin switches between 2 themes, but the way I've coded it would work for multiple color themes as well.

Here's a video explanation on how I would solve this

 

Squarespace 7.1 color themes

Squarespace 7.1 has 10 different color themes that are easy to edit. The way they work is by adding a specific CSS class to the sections. 

Here are the CSS classes and matching color themes:

  1. LIGHTEST 1: .white
  2. LIGHTEST 2: .white-bold
  3. LIGHT 1: .light
  4. LIGHT 2: .light-bold
  5. BRIGHT 1: .bright-inverse
  6. BRIGHT 2: .bright
  7. DARK 1: .dark
  8. DARK 2: .dark-bold
  9. DARKEST 1: .black
  10. DARKEST : .black-bold

So basically, the way to code the functionality you're describing we would make a function that would add a specific css class to all sections on the page, thus making the entire page have a specific theme. The only smart way is to take advantage of the Squarespace 7.1 color themes!

This function would remove the "wrong classes" from each section:

// ℹ️ HELPER FUNCTION FOR REMOVING ALL THEME CLASSES EXCEPT DARK MODE CLASS
var removeNonDarkModeClasses = function(){
var themeClasses = ['white', 'white-bold', 'light', 'light-bold', 'bright-inverse', 'bright', 'dark', 'dark-bold', 'black', 'black-bold'];
//console.log("themeClasses: " + themeClasses);

var filteredArray = themeClasses.filter(function(e) { return e !== darkModeClassName })

//console.log("other section classes but not dark mode class: " + filteredArray);

$.each(filteredArray, function( index, value ) {
    darkmodeTargetedElements.removeClass(filteredArray[index]);
});

}

 

...this would add them back.

// ℹ️ HELPER FUNCTION FOR ADDING BACK THE THEME CLASS FOR EACH SECTION
var addBackNormalNonDarkModeClass = function(){
darkmodeTargetedElements.each(function(){
	
  $(this).addClass($(this).attr("data-section-theme"));
  console.log("Adding back section class: " + $(this).attr("data-section-theme"));
  $(this).addClass($(this).attr("data-header-theme"));
  console.log("Adding back header class: " + $(this).attr("data-header-theme"));
  
}); 
}

 

This would style all the sections with a specific class from the class list above

var darkmodeTargetedElements = $(".page-section, .header");
darkmodeTargetedElements.addClass(darkModeClassName);

 

-Fenix

P.S. If you ever need help with advanced Squarespace coding, you can get in touch 🙂

P.P.S

You could also look into the source code of the soultwin.studio's website. ️ Do not copy, it's not legal.  But you can inspect and get inspired. The javascript that makes that functionality looks like this:

(function ($) {
  $(document).ready(function () {
    /* Define vars
		============================ */
    const moods = [
      {
        label: 'Editorial',
        fontFamily: 'SVG',
        fontSize: '8vw',
        letterSpacing: 0,
        color: 'f6f7f1',
        textTransform: 'uppercase',
        backgroundImage:
          '//static1.squarespace.com/static/58ef15f7d2b857e333d35434/t/5fd0df1826d54b3c06ddfc87/1607524128469/Editorial.gif',
      },
      {
        label: 'Venom',
        fontFamily: 'Font Select One',
        fontSize: device.mobile() ? '16vw' : '9.5vw',
        letterSpacing: device.mobile() ? '-3px' : '-8px',
        color: '657034',
        textTransform: 'uppercase',
        backgroundImage:
          '//static1.squarespace.com/static/58ef15f7d2b857e333d35434/t/5fd0df5aab2d482295e9d729/1607524197530/Venom.gif',
      },
      {
        label: 'Hot Embers',
        fontFamily: 'Font Select Three',
        fontSize: device.mobile() ? '12vw' : '8vw',
        letterSpacing: device.mobile() ? '-5px' : '-8px',
        color: 'F4663B',
        textTransform: 'uppercase',
        backgroundImage:
          'https://static1.squarespace.com/static/58ef15f7d2b857e333d35434/t/5fd0e0971c49363a9b566c4a/1607524514270/MOSHED-2020-12-7-21-37-46+2.gif',
      },
      {
        label: 'Lilac',
        fontFamily: 'Font Select Nine',
        fontSize: device.mobile() ? '15vw' : '8.5vw',
        letterSpacing: '-4px',
        color: 'ECE1EF',
        textTransform: 'capitalize',
        backgroundImage:
          '//static1.squarespace.com/static/58ef15f7d2b857e333d35434/t/5fc953f37fb1013a0d54db08/1607029747945/Lilac-09.jpeg',
      },
      {
        label: 'Moonflower',
        fontFamily: 'Font Select Ten',
        fontSize: device.mobile() ? '15vw' : '9vw',
        letterSpacing: device.mobile() ? '-5px' : '-10px',
        color: '7197F8',
        textTransform: 'uppercase',
        backgroundImage:
          '//static1.squarespace.com/static/58ef15f7d2b857e333d35434/t/5fd0defda4b4ef2db6b12671/1607524109876/Moonflower.gif',
      },
      {
        label: 'Dream Pop',
        fontFamily: 'Font Select Eleven',
        fontSize: device.mobile() ? '13vw' : '8.5vw',
        letterSpacing: '-4px',
        color: 'FFCFAB',
        textTransform: 'uppercase',
        backgroundImage:
          '//static1.squarespace.com/static/58ef15f7d2b857e333d35434/t/5fd0dee7b8bf0379e615c131/1607524080837/Dreampop.gif',
      },
      {
        label: 'Library Card',
        fontFamily: 'Font Select Two',
        fontSize: device.mobile() ? '16vw' : '8.75vw',
        letterSpacing: 0,
        color: 'f4f1c0',
        textTransform: 'uppercase',
        backgroundImage:
          '//static1.squarespace.com/static/58ef15f7d2b857e333d35434/t/5fc953e4c19741784c99d8b1/1607029733001/Banana-09.jpeg',
      },
      {
        label: 'Passionfruit',
        fontFamily: 'Font Select Twelve',
        fontSize: device.mobile() ? '27vw' : '12vw',
        letterSpacing: '-10px',
        color: '5B2A3D',
        textTransform: 'capitalize',
        backgroundImage:
          '//static1.squarespace.com/static/58ef15f7d2b857e333d35434/t/5fd0dffb28178304112e1a30/1607524356829/Passionfruit.gif',
      },
      {
        label: 'Limelight',
        fontFamily: 'minerva-modern',
        fontSize: device.mobile() ? '14vw' : '10vw',
        letterSpacing: 0,
        color: 'E3F4D9',
        textTransform: 'uppercase',
        backgroundImage:
          '//static1.squarespace.com/static/58ef15f7d2b857e333d35434/t/5fca42456a94db17e49c979d/1607090758096/Limelight-09.jpeg',
      },
    ];

    function autoType(elementClass, typingSpeed) {
      $('.cursor').remove();
      $('.text-js').css('opacity', 0);
      var thhis = $(elementClass);
      thhis.prepend(
        '<div class="cursor" style="right: initial; left:0;"></div>'
      );
      thhis = thhis.find('.text-js');
      var text = thhis.text().trim().split('');
      var amntOfChars = text.length;
      var newString = '';
      setTimeout(function () {
        thhis.css('opacity', 1);
        thhis.prev().removeAttr('style');
        thhis.text('');
        for (var i = 0; i < amntOfChars; i++) {
          (function (i, char) {
            setTimeout(function () {
              newString += char;
              thhis.text(newString);
            }, i * typingSpeed);
          })(i + 1, text[i]);
        }
      }, 0);
    }

    /* Make Customizer Draggable
		*- and define options
		============================ */

    _.map(moods, function (key) {
      $('#colorPickerSelect').append(`
				<div class="flex flex-align-center colors cursor-pointer">
					<div class="w-24 ht-24 cursor-pointer" data-size="${key.fontSize}" data-image="${key.backgroundImage}" data-color-label="${key.label}" data-text-transform="${key.textTransform}" data-font="${key.fontFamily}" data-let-sp=${key.letterSpacing} data-color="#${key.color}" style="background: #${key.color} content-box;"></div>
					<p class="font-7 no-transform font-size-12 m-l-spacer-md m-y-spacer-none no-transform let-sp-1 text-dark">${key.label}</p>
				</div>
			`);
    });

    autoType('.type-js', 150);

    $('#colorPickerSelect, #customizer small').hide();

    $('.pick-a-mood #handle').on('click', function () {
      $('#colorPickerSelect, #customizer small').slideDown('fast');
      $('#emptyColorState').remove();
      $('#handle-plus').hide();
      $('#handle-minus').show();
      $('#customizer').removeClass('pick-a-mood').addClass('picking-color');
    });

    $('.colorChosen #handle').on('click', function () {
      $('#colorPickerSelect, #customizer small').slideDown('fast');
      $('#handle-plus').hide();
      $('#handle-minus').show();
      $('#customizer').removeClass('colorChosen').addClass('picking-color');
      $('#activeColorContainer').hide().remove();
    });

    $('#handle-minus').on('click', function () {
      $('#colorPickerSelect, #customizer small').slideUp();
      $('#handle-plus').show();
      $('#handle-minus').hide();
      $('#customizer')
        .addClass('colorChosen')
        .removeClass('picking-color')
        .find('#colorPicker').append(`
            <div id="activeColorContainer" class="flex flex-column p-r-spacer-md">
              <div class="flex flex-align-center colors cursor-pointer active">
                <div class="w-24 ht-24 cursor-pointer" style="background: ${
                  localStorage.getItem('activeColor')
                    ? localStorage.getItem('activeColor')
                    : '#f6f7f1'
                } content-box; border-color: black"></div>
                <p class="font-5 font-size-24 m-l-spacer-md m-y-spacer-none no-transform text-dark">${
                  localStorage.getItem('activeColorLabel')
                    ? localStorage.getItem('activeColorLabel')
                    : 'Editorial'
                }</p>
              </div>
            </div>
          `);
    });

    const ACTIVECOLOREL = $('#colorPicker').find(
      `[data-color="${localStorage.getItem('activeColor')}"]`
    );

    if (localStorage.getItem('activeColor') === ACTIVECOLOREL.data('color')) {
      ACTIVECOLOREL.parent().addClass('active').find('div').css({
        borderColor: 'black',
      });

      if (localStorage.getItem('activeFont') === 'SVG') {
        $('#logoText').hide();
        $('#logoSVG').show();
        $('#logoSVG path').each(function (i) {
          var $item = $(this);
          $item.hide();
          setTimeout(function () {
            $('.cursor').removeAttr('style');
            $item.show();
          }, 150 * i);
        });
      } else {
        $('#logoSVG').hide();
        $('#logoText').show();
      }
    }

    if (!_.isNil(localStorage.getItem('activeColor'))) {
      $('#photo-container #photo-wrapper').css({
        backgroundImage: `url(${localStorage.getItem('activeImage')})`,
      });

      $('#colorPickerSelect, #customizer small').hide();
      $('#handle-plus').show();
      $('#handle-minus').hide();

      $('#handle').on('click', function () {
        $('#colorPickerSelect, #customizer small').slideDown('fast');
        $('#handle-plus').hide();
        $('#handle-minus').show();
        $('#customizer')
          .removeClass('colorChosen')
          .addClass('picking-color')
          .css({ backgroundColor: localStorage.getItem('activeColor') });
        $('#activeColorContainer').fadeOut('fast').remove();
      });

      $('#customizer')
        .addClass('colorChosen')
        .removeClass('pick-a-mood picking-color')
        .find('#colorPicker').append(`
            <div id="activeColorContainer" class="flex flex-column p-r-spacer-md">
              <div class="flex flex-align-center colors cursor-pointer active">
                <div class="w-24 ht-24 cursor-pointer" style="background: ${localStorage.getItem(
                  'activeColor'
                )} content-box; border-color: black"></div>
                <p class="font-5 font-size-24 m-l-spacer-md m-y-spacer-none no-transform text-dark">${localStorage.getItem(
                  'activeColorLabel'
                )}</p>
              </div>
            </div>
          `);

      $('#main-container').css({
        backgroundColor: localStorage.getItem('activeColor'),
      });

      $('#logoText').css({
        fontSize: localStorage.getItem('activeFontSize'),
        fontFamily: localStorage.getItem('activeFont'),
        letterSpacing: localStorage.getItem('activeLetSp'),
        textTransform: localStorage.getItem('activeTextTransform'),
      });
    } else {
      $('#customizer').append(`
          <div id="emptyColorState" class="flex flex-column p-r-spacer-md">
            <div class="flex flex-align-center cursor-pointer">
              <div class="w-24 ht-24 cursor-pointer" style="background: transparent content-box; border: 1px solid; border-color: black"></div>
              <p class="font-5 font-size-24 m-l-spacer-md m-y-spacer-none no-transform text-dark">Editorial</p>
            </div>
          </div>
				`);
				
			$('#handle-plus').on('click', function () {
				$('#colorPickerSelect, #customizer small').slideDown('fast');
				$('#handle-plus').hide();
				$('#handle-minus').show();
				$('#customizer').removeClass('colorChosen').addClass('picking-color');
				$('#activeColorContainer').hide().remove();
			});

      $('#logoSVG path').each(function (i) {
        var $item = $(this);
        $item.hide();
        setTimeout(function () {
          $('.cursor').removeAttr('style');
          $item.show();
        }, 150 * i);
      });
    }

    if (localStorage.getItem('activeFont') === 'Font Select Nine') {
      device.mobile() ? $('#logoText').css({ wordSpacing: '25px' }) : $('#logoText').css({ wordSpacing: '50px' });
    } else {
      $('#logoText').css({ wordSpacing: 0 });
    }
		
		if (localStorage.getItem('activeFont') === 'Font Select Twelve') {
      device.mobile() ? $('#logoText').css({ lineHeight: 0 }) : $('#logoText').css({ lineHeight: 0.4 });
    } else {
      device.mobile() ? $('#logoText').css({ lineHeight: 0.75 }) : $('#logoText').css({ lineHeight: 1 });
    }

    $('.select-clientele').hover(
      function () {
        $(this).removeAttr('href');
        $('.marquee').show();
      },
      function () {
        $('.marquee').hide();
      }
    );

    $('#colorPickerSelect .colors').on('click', function () {
      let color = $(this).find('div').data('color');
      let fontFamily = $(this).find('div').data('font');
      let fontSize = $(this).find('div').data('size');
      let letterSpacing = $(this).find('div').data('let-sp');
      let textTransform = $(this).find('div').data('text-transform');
      let backgroundImage = $(this).find('div').data('image');
      var v = $(this).find('p').text();

      if (fontFamily === 'SVG') {
        $('#logoText').hide();
        $('#logoSVG').show();
        $('#logoSVG path').each(function (i) {
          var $item = $(this);
          $item.hide();
          setTimeout(function () {
            $('.cursor').removeAttr('style');
            $item.show();
          }, 150 * i);
        });
      } else {
        $('#logoSVG').hide();
        $('#logoText').show();
      }

      localStorage.setItem('activeColor', color);
      localStorage.setItem('activeColorLabel', v);
      localStorage.setItem('activeFont', fontFamily);
      localStorage.setItem('activeFontSize', fontSize);
      localStorage.setItem('activeLetSp', letterSpacing);
      localStorage.setItem('activeTextTransform', textTransform);
      localStorage.setItem('activeImage', backgroundImage);

      $(this).toggleClass('active').siblings().removeClass('active');

      if ($(this).hasClass('active'))
        $(this).find('div').css({ borderColor: 'black' });

      $('#main-container').css({ backgroundColor: color });
      $('#logoText').css({
        fontFamily,
        fontSize,
        letterSpacing,
        textTransform,
      });

      if (fontFamily === 'Font Select Nine') {
        device.mobile() ? $('#logoText').css({ wordSpacing: '25px' }) : $('#logoText').css({ wordSpacing: '50px' });
      } else {
        $('#logoText').css({ wordSpacing: 0 });
			}
			
			if (fontFamily === 'Font Select Twelve') {
        device.mobile() ? $('#logoText').css({ lineHeight: 0 }) : $('#logoText').css({ lineHeight: 0.4 });
      } else {
        device.mobile() ? $('#logoText').css({ lineHeight: 0.75 }) : $('#logoText').css({ lineHeight: 1 });
      }

      autoType('.type-js', 150);

      $('#photo-container #photo-wrapper').css({
        backgroundImage: `url(${backgroundImage})`,
      });

      if (!$('#customizer').hasClass('colorChosen')) {
        $('#colorPickerSelect, #customizer small').slideUp();
        $('#handle-plus').show();
				$('#handle-minus').hide();
        $('#customizer')
          .addClass('colorChosen')
          .removeClass('picking-color')
          .css({ backgroundColor: color })
          .find('#colorPicker').append(`
            <div id="activeColorContainer" class="flex flex-column p-r-spacer-md">
              <div class="flex flex-align-center colors cursor-pointer active">
                <div class="w-24 ht-24 cursor-pointer" style="background: ${color} content-box; border-color: black"></div>
                <p class="font-5 font-size-24 m-l-spacer-md m-y-spacer-none no-transform text-dark">${v}</p>
              </div>
            </div>
		    	`);
      }
    });
  });
})(jQuery);

 

Edited by codeandtonic

Freelance Squarespace developer making plugins like Full-Width Blocks, Hover effects for grid gallery and the Darkmode plugin. I know Squarespace inside out and I'm able to solve pretty much any Squarespace code problem.

Get in touch here!

Create an account or sign in to comment

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

×
×
  • Create New...

Squarespace Webinars

Free online sessions where you’ll learn the basics and refine your Squarespace skills.

Hire a Designer

Stand out online with the help of an experienced designer or developer.