Switch between dark and light themes on the Tradingview widget

I have integrated a TradingView widget into my website and I am working on adding a dark/light mode switch to the site. I would like the widget color to change along with the background in the switch. See Widget Screenshot

TradingView Widget - Widget source

In the screenshot, you can observe that the widget has white color on the top panel and right-side panel while the chart itself is black. How can I adjust these sides to change with the toggle switch as well?

Here is the JS code for the theme switch.

const ThemeAliases = {
    dark: 'dark',
    light: 'light'
}

const setTheme = (theme) => {
    document.documentElement.setAttribute('data-theme', theme);
    localStorage.setItem('theme', theme); //add this
    __onThemeChange(ThemeAliases[theme]);
};

/* This switch toggles between dark and light mode on the entire website. */
const toggleSwitch = document.querySelector('.theme-switch input[type="checkbox"]');

toggleSwitch.addEventListener('change', switchTheme, false);

function switchTheme(e) {
    setTheme(e.target.checked ? 'dark' : 'light');
}

const currentTheme = localStorage.getItem('theme') ? localStorage.getItem('theme') : null;
let loadedTheme = null;
// This function remembers the last theme selected and saves it for the next user visit on the website
if (currentTheme) {
    document.documentElement.setAttribute('data-theme', currentTheme);
    toggleSwitch.checked = currentTheme === 'dark';
    loadedTheme = ThemeAliases[currentTheme];
}

Widget code

<div class="tradingview-widget-container">
    <div id="tradingview_4ff31"></div>
    <div class="tradingview-widget-copyright"><a href="https://www.tradingview.com/symbols/BINANCE-BTCUSDT/" rel="noopener" target="_blank"><span class="blue-text">BTCUSDT Chart</span></a> by TradingView</div>
    <script type="text/javascript" src="https://s3.tradingview.com/tv.js"></script>
    <script type="text/javascript">
        new TradingView.widget({
            "width": 2600,
            "height": 750,
            "symbol": "BINANCE:BTCUSDT",
            "interval": "1",
            "timezone": "Europe/Helsinki",
            "theme": "loadedTheme || ThemeAliases.light",
            "style": "1",
            "locale": "en",
            "toolbar_bg": "#f1f3f6",
            "enable_publishing": false,
            "allow_symbol_change": true,
            "calendar": true,
            "news": [
                "stocktwits",
                "headlines"
            ],
            "container_id": "tradingview_4ff31"
        });
    </script>
</div>

CSS

:root {
    --primary-color: rgb(82, 80, 144);
    --secondary-color: #536390;
    --font-color: #424242;
    --bg-color: #fff;
    --heading-color: #292922;
    --color: black;
}

[data-theme="dark"] {
    --primary-color: rgb(107, 106, 134);
    --secondary-color: #818cab;
    --font-color: #e1e1ff;
    --bg-color: #131722;
    --heading-color: #63656d;
    --color: white;
}

body {
    background-color: var(--bg-color);
    color: var(--font-color);
}

h1 {
    color: var(--secondary-color);
}

a {
    color: var(--primary-color);
}

Answer №1

I encountered a similar issue. It seems that, unlike the toolbar, the colors of the chart are saved in the settings. To apply the current theme to the chart, the user must reset the settings to default. This process can be quite inconvenient.

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

What is the best way to create a function that automatically resumes audio playback 3 seconds after the pause button is clicked?

I am looking to develop a basic webpage with an autoplay audio feature. The page would include a "pause" and "play" button. I aim to implement a function where clicking the "pause" button would stop the audio, but after 3 seconds, it would automatically re ...

Embracing async-await while awaiting events in node.js

I am attempting to incorporate async await into a project that is event-driven, but encountering an error. The specific error message I am receiving is: tmpFile = await readFileAsync('tmp.png'); ^^^^^^^^^^^^^ SyntaxError: Unexpec ...

angular data binding returning the identifier instead of the content

I have been dealing with managed fields retrieved from a web server in the following format: { "fields":{ "relationshipStatus":[ { "fieldId":4, "name":"Committed" }, { "fieldId":2, ...

Having trouble getting OrbitControls to function properly in Object-Oriented Programming (OOP)

Exploring the world of THREE.js and Object-oriented JavaScript. Here's the code I'm working with: https://gist.github.com/BobWassermann/581492be11db361c39ee While my browser is showing the correct output, I'm having trouble getting the Orb ...

The text from one section found its way into a different section, blending seamlessly

My Skills text is mistakenly appearing in the home-section. You can see the issue in the image below: https://i.sstatic.net/Bl2GJ.png In the provided picture, the Skills section is displayed within the home section, which is not the intended layout. It&ap ...

The checkbox generated from the JSON is failing to display the alert when it is clicked

I have been trying to pass checkbox input from JSON into HTML. When I click on the checkbox, an alert should pop up, but it's not working. Here is my code: $aroundCheck='<div id="content">'; foreach ($checkLocation as $checkLocation) ...

Prepending a string to the key of a JSON object using JavaScript

Is there a way to add 'd:' before the key of a JSON object? Here is the JSON data: "data": { "aa": "value", "ab": "value" } The expected result should look like this: "d:data": ...

Tips for seamlessly creating the animation of sketching a line

Currently, I am working on a project that involves around 40 curved lines, each containing 30 to 200 points. Despite using BufferGeometry and setDrawRange() to draw all the lines equally, only the line with over 200 points appears smooth. I attempted using ...

What sets the Test Deployment and Actual Deployment apart from each other?

I have been developing a web application using Google App Script and I currently have multiple versions of the same web app with various fields. Interestingly, when I run one version through a test deployment, it displays correctly as expected based on th ...

Send the data to be placed in the div to launch the window

I'm attempting to open a new window within the same tab and transfer some html code to be inserted into a specific div section of the newly opened window. However, I'm encountering difficulties in passing the data as illustrated below: JavaScrip ...

Tips for configuring formik values

index.js const [formData, setFormData] = useState({ product_name: 'Apple', categoryId: '12345', description: 'Fresh and juicy apple', link: 'www.apple.com' }); const loadFormValues = async () => { ...

What causes special characters to be replaced when using the 'require' function in NodeJS?

I am a beginner in JavaScript and NodeJS, so please be patient with me if this issue seems obvious. The file I have outsourced is a simple config file. Here is an abbreviated version of it: config.js: var config = {}; config.Web = {}; config.Web.Title ...

Is it possible to retrieve JSON data from an external URL using JavaScript or jQuery?

My goal is to retrieve JSON data from the following URL: I have a button that triggers the function called "jsonplz()", which should display an alert message with the fetched JSON data. This is what my JavaScript code looks like: <script src="htt ...

Trying to decide between using a Javascript or HTML5 PDF Editor?

I am in need of a solution that enables users to edit PDF files directly on an ASP.NET web page. This functionality is intended for creating templates and adding blocks/form fields to existing PDFs, complete with rulers and other necessary features. Desp ...

What language should be used for JSON data formats?

I am dealing with a JSON file named myjson.cfg that has the following structure: { "values": { "a": 1, "b": 2, "c": 3, "d": 4 }, "sales": [ { "a": 0, "b": 0, "c": 0, "d": 0, ...

Chart rendering failure: unable to obtain context from the provided item

I am encountering an issue while trying to incorporate a chart from the charts.js library into my Vue.js and Vuetify application. The error message that keeps popping up is: Failed to create chart: can't acquire context from the given item Even af ...

Updating the filter predicate of the MatTableDataSource should allow for refreshing the table content without needing to modify the filter

Currently, I am working on dynamically altering the filterPredicate within MatTableDataSource to enhance basic filtering functionalities. I want to include a fixed condition for text filtering (based on user input in a search field) for two string columns ...

Guide to incorporating an input field within a select option in ant design and react

I have utilized Ant Design to create a select option, but now I am looking to implement an editable cell within the select option. Below is the code for my select option: <Select showSearch style={{ width: 400 }} placeholder="Select a Bank" op ...

Having trouble implementing CORS in a Slim API

I'm facing challenges in setting up CORS with Slim and AngularJS. AngularJS HTTP Request: $http({ method: 'GET', headers: { 'Content-Type': 'application/json', Accepts: 'application/json&ap ...

Automatically redirect dynamic URLs to the home page in NextJS

In my NextJS project, I've set up a dynamic page that retrieves and displays blog content. The URL for this page is as follows: https://example.com/blog/[blogId] However, when attempting to access this URL on the production site, instead of landing o ...