issue arising from unique style identifiers in FireFox while making changes to styles via document.styleSheets

While experimenting with altering some stylesheets using JavaScript, I encountered an interesting issue:

When attempting to set an attribute on a style rule in Firefox and the property is one of their proprietary ones, it fails silently. To demonstrate this problem, I created an example (view live example):

<html>
<head>
<style type="text/css">
div {
    margin: 5px;
    padding: 3px;
    color: white;
}
#el1 {
    -moz-box-shadow: 2px 2px 2px red;
    -webkit-box-shadow: 2px 2px 2px red;
    -moz-border-radius: 5px;
    -webkit-border-radius: 5px;
    background: maroon;
    height: 20px;
}
#el2 {
    height: 20px;
    background:navy;
}
​
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/prototype/1.6.1.0/prototype.js"></script>
<script type="text/javascript">
    document.observe("dom:loaded", function() {
        var myStyles = $A(document.styleSheets).last();
        var rules = myStyles.cssRules || myStyles.rules;

        var el1 = rules[rules.length-2],
            el2 = rules[rules.length-1];

        //works
        el1.style["background"] = "#030";

        if (Prototype.Browser.WebKit) {
            //works
            console.log("setting webkit proprietaries");
            el2.style["-webkit-box-shadow"] = "2px 2px 2px blue";
            el2.style["-webkit-border-radius"] = "5px";

        } else if (Prototype.Browser.Gecko) {
            // does not work?!
            console.log("setting moz box-shadow");
            el2.style["-moz-box-shadow"] = "2px 2px 2px blue";
            el2.style["-moz-border-radius"] = "5px";
        }
    });
</script>
</head>
<body>
  <div id="el1">Element 1<div>  
  <div id="el2">Element 2<div>
</body>
</html>

Although I am using Fx 3.6.10 and successfully changing the background color of el1 to green, I am unable to see the drop shadow and border radius on el2 in Firefox, unlike in WebKit (Chrome and Safari).

It appears that setting rule.style[propName] = value works for standard options but not for -moz- options. Why does this happen and is there a workaround?

Answer №1

When dealing with -moz- options, it appears that removing the dashes and capitalizing the first letter of each word is necessary:

    } else if (Prototype.Browser.Gecko) {
        // Does it work now?
        console.log("setting moz box-shadow");
        // Switched color to red for better contrast
        el2.style["MozBoxShadow"] = "2px 2px 2px red";
        el2.style["MozBorderRadius"] = "5px";
    }

I discovered this by iterating through all elements of el2.style and displaying them:

for(var i in el2.style) {
    console.log('el2.style[' + i + ']: ' + el2.style[i]) ;
}

Answer №2

For those who prefer using the CSS property names over their DOM equivalents, you can opt for the following approach:

element.style.setProperty("-moz-box-shadow", "2px 2px 2px red", "");

as opposed to:

element.style.MozBoxShadow = "2px 2px 2px red";

or:

element.style["MozBoxShadow"] = "2px 2px 2px red";

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

Challenges faced during the implementation of a personalized transport system in Sentry

Struggling to set up a custom transport for my react app within a UWP container. The fetch API in the UWP environment isn't cooperating with sending events to Sentry, which I discovered after a lengthy debugging session. It appears that the fetch API ...

Having trouble aligning page in the center with flexbox and styled components

Hey there, I'm having some trouble figuring out how to center my page using flexbox within styled components in a Next.js app. Any suggestions or tips? Let me share with you my Blog Component import ReactMarkdown from 'react-markdown' impor ...

Save message in the callback function of the express app.listen method

I'm currently integrating winston logging into my application and aiming to switch all info or error level logs with winston's .info and .error. Everything seems to be working well except when trying to log an info message from within the app.lis ...

What steps can be taken to ensure that the JavaScript fetch() function is consistently accessing and updating the new data that is being added to the

I'm facing an issue with my JSON data file that I want to display on the screen. I have a function with a fetch() request that executes every time I click a button. Initially, it works perfectly by fetching the data and displaying it correctly. Howeve ...

Is there a potential white-space issue with jQuery CSS in Internet Explorer versions 7 and 8

Recently, we encountered an unusual issue with jQuery and CSS while working on compatibility with IE7 and IE8. Our project involves animations and height measurements, and during the animations, we wanted to prevent text from wrapping. To achieve this, we ...

It is necessary to render React Native text strings within a text component

Greetings! The React Native code snippet below is responsible for rendering a user interface. However, upon running the code, an error occurred. How can I resolve this issue? The error message indicates that text strings must be rendered within a text comp ...

Update the second mouse click functionality using jQuery

I currently have a jQuery function integrated into my WordPress portal that manages the functionality of the menu and the display of subcategories to ensure proper mobile optimization. This code, which was created by the theme editor, handles these aspects ...

Unable to adjust the size of the font within a text field component in Material UI

I'm currently delving into learning Material UI and am faced with the task of enlarging the text field on my webpage. Despite embedding styles along with the field, the height, width, and other properties change except for the size. Here's the sn ...

altering a PHP variable via a JavaScript variable in a query string

My current task involves validating textbox input against a specific set of words in a predefined order from the database to check for matches. Upon successful validation, the user's "quest" level increments, triggering a new set of words to be fetche ...

Increase the lag time for the execution of the on('data') function in Node.js

In my current function, it searches data from a database and performs an action with it. For the purpose of this demonstration, it simply increments a counter. exports.fullThreads = function(){ return new Promise((resolve, reject) => { MongoClien ...

Keeping track of the toggle state using a cookie

While searching for a way to retain the toggle state, I stumbled upon js-cookie on GitHub. The documentation provides instructions on creating, reading, and deleting a cookie. However, an example would have been really helpful in enhancing my understanding ...

css side by side with immovable element

Seeking assistance with CSS. I am looking to create a layout as follows: I want a center-fixed menu with a width of 960px - this part is straightforward. Alongside the menu, I aim to have two divs: one spanning from the left edge of the screen to the cl ...

Having trouble updating the input value in AngularJS?

As I venture into customizing an AngularJS tutorial on a Saturn Quiz, I am transforming it from multiple choice to a fill-in-the-blank quiz. The challenge I face is that the first answer registers as correct or incorrect, but subsequent questions always s ...

Problems arising from the layout of the PrimeNG DataView component when used alongside Prime

I've been working with a PrimeNG DataView component that requires the use of PrimeFlex's flex grid CSS classes to set up the grid structure. One of their examples includes the following instructions: When in grid mode, the ng-template element ...

Error TS2322: The object with properties "ready: false" and "session: null" cannot be assigned to the type "Readonly<S & withAuthState>"

Here is the interface I'm currently working with: export interface withAuthState { ready: boolean, session: any } Additionally, I have developed the following Higher Order Component (HOC): const withAuth = <P extends withAuthProps, S extends ...

Trouble with Flex 3 styles not fully applying to dynamically generated tabs within a TabNavigator

When using ActionScript to dynamically create a tab, I noticed that the style is applied to the skins but not to the text of the newly created tab until I click on another tab and then go back to it. ActionScript private function clickAddTabHandler(event ...

Modifying the HTML attribute value (of input) does not impact the value property

After inputting a single tag, I ran the following code in my Chrome console: https://i.stack.imgur.com/ySErA.jpg The result was unexpected for me. According to what I have read in a book, when I change an HTML attribute, the corresponding property should ...

Interactive feature in Three.js causes page to scroll downwards upon object selection

Exploring Three.js for the first time, I'm looking to integrate it into the landing page of my website. However, I've encountered an issue where clicking on the scene area with my object causes the page to shift downward. I've tried adding o ...

Looking for tips on how to achieve a sleek search bar expansion effect when focusing using w3.css?

I have been trying to utilize the following code to create a Google search bar that expands when focused within a w3.css navigation bar-item. While it does expand and contract on focus/blur, I am unable to achieve smooth transitions between sizes. The sear ...

Do frameworks typically result in redundant CSS declarations?

Working on my latest Wordpress theme project, I have integrated the Bootstrap framework. One of the styles included in the Bootstrap CSS file is: input, textarea, .uneditable-input { width: 206px; } This style rule is causing issues with how my search ...