Ways to obtain a compilation of personalized CSS attributes

Exploring the world of custom CSS properties, I have crafted the code below.

If I embed the CSS directly within the canvas tag using a STYLE attribute (like this: style="--rgLinewidth: 3" ), then I am able to access these custom CSS values with the script provided below.

However, when using a <style> tag as shown below, the custom CSS properties do not display.

Is there a way to accomplish this? If so, how?

<html>
    <head>
        <style>
            canvas#cvs {
                --rgLinewidth: 3;
                background-color: red;
            }
        </style>
    </head>
<body>

    <canvas id="cvs" width="600" height="250">[No canvas support]</canvas>

     <script>
        canvas = document.getElementById("cvs");
        styles = window.getComputedStyle(canvas);

        alert(styles.getPropertyValue('background-color'));
        alert(styles.getPropertyValue('--rgLinewidth'));

        for (var i=0; i<styles.length; i++) {
            if (canvas.style[i].indexOf('--rg') === 0) {
                var value = styles.getPropertyValue(canvas.style[i]);
                alert([canvas.style[i], value]);
            }
        }
    </script>
</body>
</html>

Answer №1

When attempting to retrieve values of corresponding properties from the inline style of an element, it won't work if the element does not define an inline style like your canvas. To fetch these values, you should query the values through the same styles object instead of trying to access them directly from the inline style.

Here is a function that searches for the value of the first CSS variable starting with --rg in the computed style of an element:

function find_first_rg_value(el) {
    var styles = getComputedStyle(el);
    for (var i = 0; i < styles.length; i++) {
        if (styles[i].startsWith('--rg')) {
            return styles.getPropertyValue(styles[i]);
        }
    }
}

(You can use this function by passing the canvas element as an argument: find_first_rg_value(canvas))

The key difference between my approach and yours is that querying the value using canvas.style[i] won't work since canvas.style is empty. It's essential to utilize the styles object instead.

Computed style obtained through getComputedStyle encompasses the summary style calculated through CSS cascading, inheritance, and any inline styles applied on top. While assigning an inline style influences the computed style, querying inline style only returns the explicitly assigned inline styles.

In scenarios like yours, utilizing getComputedStyle is recommended. Additionally, for accessing CSS variables, irrespective of dealing with inline or computed styles, getPropertyValue function must be used with dashes intact in the property name.

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

Revamping the hyperlinks in my collapsible menu extension

Is there a way to modify the links in this accordion drop menu so that they lead to external HTML pages instead of specific areas on the same page? I've tried various methods but can't seem to achieve it without affecting the styles. Currently, i ...

Position the icon to the left within a bootstrap 5 card

Struggling with alignment in Bootstrap 5, facing two issues: 1- How to align my icon with the left border of the card body? 2- Increasing the icon size affects the vertical alignment of my card item (see image below) https://i.sstatic.net/dR7DD.png Try ...

Update multiple rows in a MySQL database by using the values from an `$_

Struggling to update multiple rows in MySQL using an array from the $_POST variable named "units". Despite my efforts, I can't seem to crack this problem. Here is what I have attempted: My current code that doesn't update the 2nd person: if(iss ...

Utilizing CSS to dynamically update SVG icons within the navigation menu upon tab selection

Feeling frustrated and in need of assistance with my current issue. I am attempting to make a change - when I click on a tab in the menu, the default black SVG icon should be replaced by a white one. #menu a .main-menu-icon { display:inline-block; width:2 ...

What steps can be taken to ensure that a box is the exact same size

Is it possible to make two of my main buttons the same size? I'm just starting out in web development and could use some guidance. Below is the HTML and CSS code I currently have for my index.html: <body> <div> <img src="img/projec ...

I'm trying to align two columns side by side within a row using bootstrap, but they are continuously stacking on top of each other. Any ideas on

Why won't my columns align next to each other? They just end up stacked on top of each other. .col-sm-4{ background-color: black; opacity:0.9; height: 100%; margin: auto; position: absolute } .container-fluid{ padding: 0; } .row{ mar ...

Elements within the CSS grid are misaligned

After spending hours on it, aligning my grid elements vertically seems like a simple task that I just can't seem to crack. Check out the fiddle for a better idea of what I'm talking about. Any help with this issue would be greatly appreciated. H ...

Passing a variable to the render method in a PDF document

I'm currently working on a project with Django where I need to convert an HTML monthly report into a PDF. The data for the report is retrieved from a database based on the selected month. I am facing an issue in sending the selected month from the HTM ...

How do I integrate a button into my grey navigation bar using tailwindcss in REACT?

Is it possible to integrate the - button into the gray bar? I am encountering an issue where my blue button extends beyond the borders of the gray bar in the image provided. export default function App() { ... return ( <div className="text-md fon ...

Tips for swapping out a sticky element as you scroll

Context As I work on developing a blog website, I aim to integrate a sticky element that dynamically updates according to the current year and month as users scroll through the content. This would provide a visual indication of the timeline for the listed ...

What is the process for creating a sub-menu for a dropdown menu item in Bootstrap 5?

https://i.sstatic.net/o4FLn.pngthis is my code which i have created this navigation bar with bootstrap and all of its drop downs but i want to add another drop down to the services drop down section inside of webdevelopment but it can't any easy solut ...

What is the best way to display a unique image in a div based on the size of the

Being new to web design, I have a question about creating a webpage with a large image in the center like on GitHub's Windows page. How can I work with the image inside that particular div or area based on different screen sizes? Is it possible to mak ...

In what way can the button display the permission directly on the page?

When the website notification is granted, a green button should be displayed. If it is denied, show a red button instead. The button comes with a CSS style and a checkbox but does not have the permission to grant or allow any permissions on the page. Butt ...

Header spanning the entire width with varying ends

Hello everyone, I'm currently working on a website and struggling to create a header similar to the image shown above. I want the header to span the full width of the page. Can anyone provide guidance on achieving this using HTML5/CSS3 without relyin ...

Choosing Rules in CSS

My HTML page has a layout where most of the content needs to be centered, but within a specific table, I require cells to have different alignments - some left-aligned, some right-aligned, and one center-aligned. The code below demonstrates what I am tryin ...

Use the nobr HTML tag on Django form fields

I have been customizing Django form fields using this helpful guide. Here is the form structure: class contact(forms.Form): first_name = forms.CharField() middle_name = forms.CharField() last_name = forms.CharField() This is how the template ...

Generate vibrant hues using Emmet shortcuts

I am currently using Vim version 8.2 with vim-emmet version 0.86. I am struggling to write the abbreviation for CSS as shown below: border: 1px solid #dcd2ba; Upon referencing the manual, I came across the instructions for css abbreviation which can be ...

Generating Unique Random DIV IDs with JavaScript

Does anyone know of a JavaScript solution to generate unique random DIV IDs? I am currently using PHP for this purpose. <?php function getRandomWord($len = 10) { $word = array_merge(range('a', 'z'), range('A', &apos ...

Tips for increasing the size of a gwt menuitem when hovering over it

I am facing an issue with my gwt menu bar. I want to make it so that when I hover over a menu item, only that specific item grows in size. However, the problem is that when I use CSS to adjust the height of the hovered item, all menu items are affected. Ha ...

Display scroll bars in the table only when necessary

I am attempting to have scroll bars only appear in a table when necessary, while also showing colors upon hovering over rows and columns. The row and column highlighting on hover is functioning properly, but the scroll bar is persistently visible. What st ...