CSS Toggle failing to show updated styles

Initially, I successfully changed the font and color of text on Google using a simple code. However, when I attempted to incorporate it into a toggle on / off switch, the changes did not take effect.

To address this issue, I sought assistance from ChatGPT for error reduction and general guidance on my approach. Despite receiving some incorrect information, I ran numerous iterations through the prompts. However, it seems that ChatGPT can no longer detect any significant changes.

//Get the URL
const site = window.location.hostname

//Function to add custom CSS
let customStyle;
const Add_Custom_Style = css => customStyle = document.head.appendChild(document.createElement("style")).innerHTML = css;
const Remove_Custom_Style = () => customStyle.remove();

//Function to change CSS
function changeCSS(){
    //Function for Google.com
    if (site.includes("google.com")){
        Add_Custom_Style(`
        @import url('https://fonts.googleapis.com/css2?family=Advent+Pro:wght@300&display=swap');

        * {
            font-family: 'Advent Pro', sans-serif !important; 
            color: #fff !important;
        }

        a {
            color: #b0dff4 !important; 
            font-size: 140%;
        }

        h1, h2, h3, h4, h5, h6 {
            color: #b0dff4 !important;
        }
        `)
    }
}

//Function to remove CSS
function removeCSS(){
    customStyle.remove();
}

//Toggle function on off
window.onload = function() {
    const cssToggleBtn = document.getElementById("togBtn");

    cssToggleBtn.addEventListener("change", function(){
        if(cssToggleBtn.checked){
            changeCSS();
        }
        else{
            removeCSS();
        }
    });
};

This is the current code that I am using. If there are any oversights or glaring errors, I would appreciate it if you could point them out. Thank you!

Answer №1

//Extract the current URL
const currentURL = window.location.hostname

//Function to apply custom CSS
let customStyle;
const ApplyCustomStyle = (css) => {
  customStyle = document.createElement("style")
  document.head.appendChild(customStyle).innerHTML = css;
}
const RevertCustomStyle = () => customStyle.remove();

//Function to modify CSS
function modifyCSS(){
    //Function specifically for Google.com
    //if (currentURL.includes("google.com")){// Are you certain? Running this on the google.com domain?
        ApplyCustomStyle(`
        @import url('https://fonts.googleapis.com/css2?family=Advent+Pro:wght@300&display=swap');

        * {
            font-family: 'Advent Pro', sans-serif !important; 
            color: #fff !important;
        }

        a {
            color: #b0dff4 !important; 
            font-size: 140%;
        }

        h1, h2, h3, h4, h5, h6 {
            color: #b0dff4 !important;
        }
        `)
    //}
}

//Function to revert back CSS changes
function revertCSS(){
    customStyle.remove();
}

//Toggle functionality
window.onload = function() {
    const cssToggleBtn = document.getElementById("togBtn");

    cssToggleBtn.addEventListener("change", function(){
        if(cssToggleBtn.checked){
            modifyCSS();
        }
        else{
            revertCSS();
        }
    });
};
<h1>Demo</h1>
<p>
  <a href="https://google.com" target="_blank">Google</a>
</p>
<label>
  <input id="togBtn" type="checkbox">
  Toggle.
</label>

if (currentURL.includes("google.com")){
implies that the currentURL constant fetching the URL must be google.com.
Are you certain that you are executing this on the Google domain?

You have a customStyle variable and use .remove() to eliminate the <style> element, but the assignment is incorrect.

You have already defined RevertCustomStyle as a function to remove the <style> element using the customStyle variable. Therefore, there is no need to define the revertCSS() function to perform the same action again.
Choose one!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The MomentJS .format() function accurately displays the date as one day in the past in my local time

After using momentJs to display a date in a specific format in my UTC-4:30 timezone, I noticed that it skips a day. I am currently in the UTC-4:30 timezone. This issue does not occur in all timezones; it works correctly in the UTC-5:00 timezone. The fol ...

Unlock the Secrets of Soundcloud: Practical Steps to Implementing the Soundcloud API in Real Life

I attempted to publish the exact .html and .js codes on the internet and host them on my own server. I am aiming to duplicate this particular example: You can check out my code at www[dot]whatsgucci[dot]com/cloudstalk.html Here is the code I utilized: ...

The addition of special characters to strings in TypeScript through JavaScript is not functioning as expected

I need assistance on conditionally appending a string based on values from captured DOM elements. When the value is empty, I want to include the special character "¬". However, when I try adding it, I get instead because the special character is not reco ...

Struggling to align materialUI input or textfield horizontally

import {Input} from 'material-ui'; import Select from 'react-select'; I've been trying different ways to adjust the margins and padding, even wrapping them in divs, but I can't seem to get Material UI textfield or input alig ...

Is it achievable to have a background image cover size with a responsive rollover effect?

I’m currently facing a unique challenge where I want to have an image as the background of my website, with the size set to cover the entire screen. On this background image, there are elements like buildings that I want to interact with when hovered ove ...

I'm having trouble getting the "flex direction: row" property to work within a table row

First, I applied flex to the table > tr. Next, I configured the flex-direction to be row. table { width: 100%; } tr { display: flex; flex-direction: row; flex-wrap: wrap; overflow: hidden; width:100%; } td:nth-child(1) { flex: 0 0 20%; ...

Changing the position of a Bootstrap popover dynamically from top to bottom

Struggling with the bootstrap popover here. I can't seem to change the popover position from top to bottom when it reaches the top of the viewport. I attempted to use placement: 'auto bottom' but unfortunately, it didn't do the trick f ...

Tips for implementing multiple selectors in YUI

Is there a way to use multiple selectors in YUI (YUI 2) similar to jQuery? $('h1, h2, el1, el2, .content, .title').css('color', 'red'); How can I achieve the same in YUI without having to individually add classes using YAHOO ...

When using mobile browsers and the screen width is at its maximum

I am in desperate need of help with this issue, can someone please provide guidance? I am currently working on optimizing a webpage for mobile devices using CSS media queries. In the <head> section, I have included the following: <meta name="Ha ...

How can the error within a promise be captured when using resolve()?

Check out the code snippet below: userUpdate(req: Request, res: Response) { this.userTaskObj.userUpdate(req.params.id, req.body).then(() => { res.status(200).json({ status: 'OK', message: 'User updated', ...

Discover the ideal method for utilizing floating divs that overlap

I'm currently working on developing a custom Wordpress theme using PHP, HTML, and CSS. One issue I'm facing is that my footer automatically moves down below the white content block whenever I add more text. Now, I am looking to incorporate an ad ...

Display a jQuery alert when an AJAX post request exceeds its timeout limit

I have been working on creating a feature to notify users when their $.post() request times out. To achieve this, I have implemented the following code snippet: //when ajax request start show overlay $(document).ajaxStart(function(){ ...

Function that contains a JavaScript reference and observation

I'm experiencing issues with the code below and I'm having trouble figuring out what's causing the problem. function some(){ for (var i=0;i<....;i++) { var oneObject; ...some logic where this object is set oneObject.watch(prop ...

Is there a regular expression that can identify whether a string is included in a numbered list?

Struggling with creating a regular expression to determine if a string is part of a numbered list like those in word processors. Need it to return true only if the string starts with a number, followed by a full stop and a space. Easy for single or doubl ...

What are the steps to address the Invalid Hook Call issue while working with Material UI?

Having an issue with a MaterialUI Icon in my code as a newcomer to coding. Here is the snippet: import PersonIcon from '@mui/icons-material/Person'; function Header() { return ( <div> <PersonIcon /> <h2>Header file</h2 ...

Capturing the process exit event in Express: A guide

process.on('exit', async () => { console.log('updating') await campaignHelper.setIsStartedAsFalse() console.log('exit') process.exit(1) }) This code snippet is designed to trigger an update in the database before t ...

Assistance needed for jQuery functions running too early

Within my click function, I am setting certain flags and then calling two functions. However, I want these two functions to execute sequentially in order after the flags have been set. jQuery("#element").click(function(e){ var op = jQuery("#box" ...

Guiding users who have disabled JavaScript through redirection

When faced with the following markup, users whose browser has JavaScript disabled will be redirected to an alternative page. This alternate page may attempt to mimic the site's functionality without JavaScript or simply display a warning message infor ...

Guide on setting a personalized color for progress bars in Bootstrap 4

I'm working on a progress bar: <div class="progress"><div class="progress-bar" style="width:{{a.49}}%">{{a.49}} %</div> </div> Is there a way to apply a custom color to the progress bar based on a condition in CSS? : If a.49 ...

Can you transform text with accents into plain ASCII characters?

I am seeking a solution in Javascript to convert accented letters and various encodings into plain English ASCII characters. The goal is to achieve the following transformations: éclair ~becomes~ eclair bär ~becomes~ bar привет ~becomes~ privet ...