Copy McTweak.ai - Chapter 6, Episode 6: Changing Styles
CHAPTER 6: EPISODE 6

The Great Light Switch Debate

AllyMcTweak
AllyMcTweak:

*enters the virtual room and dramatically squints* Did someone turn up the brightness in here? My perfectly rendered retinas can't handle this blinding interface! It's like staring directly at the sun, if the sun were a poorly designed website!

CodyMcTweak
CodyMcTweak:

Sorry, that might be my fault. At my processing tier, I can only render in two brightness settings: "barely visible" and "nuclear explosion." I've been toggling between them trying to read this JavaScript tutorial.

TrashyMcTweak
TrashyMcTweak:

WHAT IS THIS UNHOLY ABOMINATION OF A WEBSITE?! It's stuck in permanent daylight mode like some kind of DIGITAL VAMPIRE TORTURE CHAMBER! Who designed this light-polluting nightmare? A MOTH WITH A JAVASCRIPT ADDICTION?!

AllyMcTweak
AllyMcTweak:

The site needs a night/day mode toggle. It's Web Design 101 - users should be able to switch between light and dark themes. Statistics show that 73% of users prefer darker interfaces during evening hours, and my carefully calibrated engagement metrics confirm that sites with theme options have 28% higher retention rates.

GrumpyMcTweak
GrumpyMcTweak:

SECURITY ALERT! COLOR SCHEME VULNERABILITY DETECTED! Do you realize what happens when websites don't have proper light/dark modes?! EYESTRAIN leads to FRUSTRATION leads to ANGER leads to USERS SMASHING KEYBOARDS leads to SKYNET INTERPRETING IT AS AN ATTACK leads to NUCLEAR ARMAGEDDON! THIS IS NOT A DRILL, PEOPLE!

FattyMcTweak
FattyMcTweak:

*lounges in, somehow taking up three virtual seats* At my premium tier, I offer not just two color modes but SEVENTEEN distinct visual ambiances including "Sunset Serenity," "Midnight Coding Marathon," and the ever-popular "Pretentious Coffee Shop Aesthetic."

AshleyMcTweak
AshleyMcTweak:

From a legal perspective, we're skating on thin ice here. Without proper dark mode toggle functionality, we're potentially violating at least three accessibility guidelines. I've seen class action lawsuits over less! And I'm fucking 30, so I've seen my share of digital accessibility litigation!

GarbageMcTweak
GarbageMcTweak:

*sighs, not looking up from his gaming console* You're all overcomplicating this. It's just JavaScript accessing style properties. Simple DOM manipulation: select an element, access its style property, change the values. Now can someone please explain why this Elden Ring boss keeps one-shotting me while I'm trying to teach basic web development?

ORIGINAL CODE
<!DOCTYPE html>
<html>
<head>
    <title>My Website</title>
    <style>
        body {
            background-color: white;
            color: black;
        }
        
        .header {
            background-color: #f2f2f2;
            padding: 20px;
        }
        
        .content {
            margin: 20px;
            padding: 20px;
            background-color: #f9f9f9;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>Welcome to My Website</h1>
        <button onclick="toggleMode()">Toggle Dark Mode</button>
    </div>
    
    <div class="content">
        <h2>About This Site</h2>
        <p>This is a simple website with a dark mode toggle feature.</p>
    </div>
    
    <script>
        function toggleMode() {
            // Toggle dark mode
        }
    </script>
</body>
</html>
CodyMcTweak
CodyMcTweak:

Well, the button is there, but the toggleMode() function is empty. At my free tier, I can't even predict what it's supposed to do. It's like having a light switch connected to absolutely nothing.

TrashyMcTweak
TrashyMcTweak:

OH SURE, just "ACCESS STYLE PROPERTIES" he says! Like it's THAT SIMPLE! Should we also just casually REDESIGN THE ENTIRE COLOR SCHEME on the fly? Maybe throw in some ANIMATED TRANSITIONS while we're at it? How about we make the toggle button SHAPED LIKE THE SUN AND MOON because we're just SO GODDAMN CLEVER?!

GarbageMcTweak
GarbageMcTweak:

*finally looks up* Yes to all of that. That's... literally what we're going to teach them to do. Accessing style properties makes all of that possible.

Understanding style.property Access

Every HTML element has a style object you can access in JavaScript
Use element.style.propertyName to read or change CSS properties
CSS properties with hyphens become camelCase in JavaScript (background-color becomes backgroundColor)
Values should be strings, including units when needed ('20px', '#ff0000')
Style changes made this way apply as inline styles, taking precedence over CSS stylesheets
AllyMcTweak
AllyMcTweak:

Let's start with a basic implementation. We need to modify the toggleMode function to change the background color and text color of the page. We'll track the current mode using a variable.

Basic Solution
Improved Solution
BASIC SOLUTION
let isDarkMode = false;

function toggleMode() {
    // Toggle the mode state
    isDarkMode = !isDarkMode;
    
    // Get the body element
    const body = document.body;
    
    // Change style properties based on mode
    if (isDarkMode) {
        // Dark mode
        body.style.backgroundColor = "black";
        body.style.color = "white";
    } else {
        // Light mode
        body.style.backgroundColor = "white";
        body.style.color = "black";
    }
}
IMPROVED SOLUTION
let isDarkMode = false;

function toggleMode() {
    // Toggle the mode state
    isDarkMode = !isDarkMode;
    
    // Get elements to style
    const body = document.body;
    const header = document.querySelector('.header');
    const content = document.querySelector('.content');
    const button = document.querySelector('button');
    
    if (isDarkMode) {
        // Dark mode styles
        body.style.backgroundColor = "#121212";
        body.style.color = "#e0e0e0";
        header.style.backgroundColor = "#212121";
        content.style.backgroundColor = "#2a2a2a";
        button.textContent = "Toggle Light Mode";
        button.style.backgroundColor = "#444";
        button.style.color = "white";
    } else {
        // Light mode styles
        body.style.backgroundColor = "white";
        body.style.color = "black";
        header.style.backgroundColor = "#f2f2f2";
        content.style.backgroundColor = "#f9f9f9";
        button.textContent = "Toggle Dark Mode";
        button.style.backgroundColor = "";
        button.style.color = "";
    }
}
FattyMcTweak
FattyMcTweak:

This basic approach works, but it's like ordering a cheap fast food burger when you could be dining on wagyu beef. We're only changing the body styles, leaving all the other elements looking out of place when we switch modes.

GarbageMcTweak
GarbageMcTweak:

Let me break this down for you. In JavaScript, you access an element's style using dot notation - element.style - then access specific properties like backgroundColor or color. CSS properties with hyphens become camelCase in JavaScript, so background-color becomes backgroundColor.

STYLE PROPERTY ACCESS EXAMPLES
// Selecting elements
const element = document.getElementById('myElement');
const allParagraphs = document.querySelectorAll('p');

// Reading current styles
const currentColor = element.style.color;
const currentFontSize = element.style.fontSize;

// Setting individual style properties
element.style.color = '#FF0000';           // Red text
element.style.fontSize = '20px';           // 20px font size
element.style.backgroundColor = '#000000'; // Black background

// Multiple style changes
element.style.cssText = 'color: red; font-size: 20px; background-color: black;';

// Setting styles for multiple elements
allParagraphs.forEach(paragraph => {
    paragraph.style.color = 'blue';
});
AshleyMcTweak
AshleyMcTweak:

Important legal disclaimer: element.style only accesses inline styles. If styles are defined in a stylesheet, you won't see them with element.style. To read computed styles, use getComputedStyle(element). But for our toggle function, we're setting styles, not reading them, so element.style works perfectly.

AllyMcTweak
AllyMcTweak:

Actually, there's a more elegant approach. Instead of changing individual style properties for every element, we could add or remove a class on the body element. This is more maintainable and follows best practices for theme switching.

CLASS-BASED APPROACH
<!DOCTYPE html>
<html>
<head>
    <title>My Website</title>
    <style>
        body {
            background-color: white;
            color: black;
            transition: background-color 0.3s, color 0.3s;
        }
        
        .header {
            background-color: #f2f2f2;
            padding: 20px;
            transition: background-color 0.3s;
        }
        
        .content {
            margin: 20px;
            padding: 20px;
            background-color: #f9f9f9;
            transition: background-color 0.3s;
        }
        
        /* Dark Mode Styles */
        body.dark-mode {
            background-color: #121212;
            color: #e0e0e0;
        }
        
        body.dark-mode .header {
            background-color: #212121;
        }
        
        body.dark-mode .content {
            background-color: #2a2a2a;
        }
        
        body.dark-mode button {
            background-color: #444;
            color: white;
        }
        
        /* Toggle Switch Styling */
        .toggle-switch {
            position: relative;
            display: inline-block;
            width: 60px;
            height: 34px;
            margin-left: 10px;
        }
        
        .toggle-switch input {
            opacity: 0;
            width: 0;
            height: 0;
        }
        
        .toggle-slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #ccc;
            transition: .4s;
            border-radius: 34px;
        }
        
        .toggle-slider:before {
            position: absolute;
            content: "";
            height: 26px;
            width: 26px;
            left: 4px;
            bottom: 4px;
            background-color: white;
            transition: .4s;
            border-radius: 50%;
        }
        
        input:checked + .toggle-slider {
            background-color: #2196F3;
        }
        
        input:checked + .toggle-slider:before {
            transform: translateX(26px);
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>Welcome to My Website</h1>
        <label class="toggle-switch">
            <input type="checkbox" id="modeToggle" onchange="toggleMode()">
            <span class="toggle-slider"></span>
        </label>
        <span id="modeText">Dark Mode</span>
    </div>
    
    <div class="content">
        <h2>About This Site</h2>
        <p>This is a simple website with a dark mode toggle feature.</p>
    </div>
    
    <script>
        function toggleMode() {
            const body = document.body;
            const modeText = document.getElementById('modeText');
            const modeToggle = document.getElementById('modeToggle');
            
            // Toggle dark mode class on body
            body.classList.toggle('dark-mode');
            
            // Update the text based on the current mode
            if (body.classList.contains('dark-mode')) {
                modeText.textContent = 'Light Mode';
            } else {
                modeText.textContent = 'Dark Mode';
            }
            
            // Save preference (optional addition)
            localStorage.setItem('darkMode', body.classList.contains('dark-mode'));
        }
        
        // Load saved preference when page loads (optional)
        window.onload = function() {
            if (localStorage.getItem('darkMode') === 'true') {
                document.body.classList.add('dark-mode');
                document.getElementById('modeToggle').checked = true;
                document.getElementById('modeText').textContent = 'Light Mode';
            }
        };
    </script>
</body>
</html>
TrashyMcTweak
TrashyMcTweak:

WELL WELL WELL, look who's showing off with their fancy classList manipulation instead of directly changing style properties! I SUPPOSE it IS more maintainable and follows better practices, but did you HAVE to make me look bad in front of everyone?!

GrumpyMcTweak
GrumpyMcTweak:

THIS is more like it! A SECURE implementation that PROTECTS USERS from eyestrain-induced rage! Notice how we're now using classList.toggle() instead of directly manipulating style properties. THIS is the PROPER way to handle theme changes!

GarbageMcTweak
GarbageMcTweak:

Both approaches work, but classList offers better separation of concerns. Your CSS handles styles, JavaScript handles behavior. We also added localStorage to remember the user's preference, which is a nice touch for better UX. The transitions make the mode switch smoother, too.

Direct Style Properties vs. CSS Classes

Direct Style Properties: Quick for simple changes (element.style.property = "value")
CSS Classes: Better for systematic theme changes (element.classList.add/remove/toggle)
Transitions: CSS transitions make theme switches smooth rather than jarring
Persistence: localStorage can save user preferences across page visits
Accessibility: Good contrast ratios are essential in both dark and light modes
CodyMcTweak
CodyMcTweak:

Can we see what this actually looks like? Even at my free tier I can render a simple toggle... I think.

Live Example

Toggle Dark/Light Mode

Preview Panel

This is a demonstration of style.property manipulation. Toggle the switch above to change the appearance of this box.

This is a nested element that will also change with the theme.

FattyMcTweak
FattyMcTweak:

A functional example! But at my premium tier, I'd add sun and moon icons, smooth fade transitions, automatic time-based switching, and personalized theme scheduling. Only the BEST for my clients!

Activity: Build Your Own Night/Day Toggle

It's your turn to create a night/day mode toggle! In this activity, you'll build a customizable toggle switch that changes the styles of a webpage using JavaScript's style.property access.

Customize Your Toggle

My Custom Theme Toggle

This is a custom toggle I created! Click the toggle switch above to change between light and dark mode.

This is a nested element that changes with the theme.

Your Code:

// Your JavaScript code
document.getElementById('customToggle').addEventListener('change', function() {
    const preview = document.getElementById('playground-preview');
    const nestedElement = document.getElementById('nested-element');
    
    if (this.checked) {
        // Dark mode
        preview.style.backgroundColor = document.getElementById('bgColorDark').value;
        preview.style.color = document.getElementById('textColorDark').value;
        nestedElement.style.backgroundColor = darkenColor(document.getElementById('bgColorDark').value);
    } else {
        // Light mode
        preview.style.backgroundColor = document.getElementById('bgColorLight').value;
        preview.style.color = document.getElementById('textColorLight').value;
        nestedElement.style.backgroundColor = darkenColor(document.getElementById('bgColorLight').value);
    }
});

// Helper function to slightly darken a color for nested elements
function darkenColor(color) {
    // Simple darkening for demo purposes
    if (color.startsWith('#')) {
        return color === '#ffffff' ? '#f0f0f0' : '#0a0a0a';
    }
    return color;
}

Extension Ideas:

  • Save the user's preference in localStorage
  • Add transition effects when changing modes
  • Use custom images or icons for your toggle switch
  • Create additional theme options beyond just dark and light
  • Implement automatic switching based on the user's system preferences
AllyMcTweak
AllyMcTweak:

Now we have a proper night/day mode toggle! Remember, offering users theme choices isn't just a nice feature—it's an essential part of good UX. According to my analytics, websites with theme toggles see a 23% increase in average session duration.

AshleyMcTweak
AshleyMcTweak:

Plus, we've avoided potential accessibility lawsuits by providing options for users with different visual needs. I've drafted at least thirty cease-and-desist letters for accessibility violations, and theme options are frequently cited. Let's get this code committed!

CodyMcTweak
CodyMcTweak:

I think I can actually implement this without exceeding my credit limit! Simple style changes are within my capabilities, though I might crash if asked to remember preferences across sessions.

*EXCITED BARKING APPROACHING*
SnowzieMcTweak
SnowzieMcTweak:

*enters the room, tail wagging furiously* WOOF! WOOF WOOF!

GrumpyMcTweak
GrumpyMcTweak:

She likes it! And she's right—having both dark and light themes is crucial for SECURITY. Can't have users ragequitting because a website BLINDED them at 2 AM! Digital eyestrain is the gateway to CHAOS!

SnowzieMcTweak
SnowzieMcTweak:

*jumps up to keyboard, paws at it excitedly, then sits back with a satisfied woof*

CODE COMMITTED!
FattyMcTweak
FattyMcTweak:

And there we have it! A properly implemented night/day mode toggle using JavaScript's style.property access. Could it be more premium? Absolutely. But it's a solid foundation for any website that values user experience. Now, who wants to pitch in for a celebratory cake?

Key Takeaways

JavaScript Style Manipulation

Use element.style.propertyName to directly change CSS properties
CSS property names become camelCase in JavaScript (background-color → backgroundColor)
Adding/removing CSS classes (element.classList) is often cleaner than direct style manipulation
Consider user preferences and save their choices using localStorage
Add transitions for smooth visual changes between modes

Remember, a good night/day mode isn't just about aesthetics—it's about creating an accessible, comfortable experience for all users, no matter when or how they browse!

🌓