mozilla
Your Search Results

    JavaScript

    This makes sense to me - but where I run into problems is -retrieving- CSS element data.

    Basically what I have found is that I cannot read the values that were set in the CSS file. Once the value is set via javascript I can read it in javascript, otherwise, I'm out of luck. Any suggestions are welcome.


    Here is an example:

    In the CSS file:

    #square {
     position: fixed; 
     width: 20em;
     height: 20em;
     border: 2px inset gray;
     margin-bottom: 1em;
     left: 200px;
     top: 200px;
     background-color: green;
     }
    

    Change the javascript:

    function doDemo (button) {
     var square = document.getElementById("square")
     alert("BackgroundColor: " + square.style.backgroundColor);  // Returns nothing
     square.style.backgroundColor = "#fa4"
     alert("BackgroundColor: " + square.style.backgroundColor);  // Returns #fa4 as expected  
     
     button.setAttribute("disabled", "true")
     setTimeout(clearDemo, 2000, button)
     }
    

    -- Spark343

    This is not a good place to discuss JavaScript programming techniques. I suggest one of mozillaZine's Development forums is probably a better place.

    Briefly, there are three ways to work with CSS in JavaScript. This page shows the third way: "working with an individual element in the DOM—modifying its style independently of the document's stylesheets". You cannot work with a value in a stylesheet this way.

    To work with a value in a stylesheet you can use the first two ways. For example, you can write:

    alert(document.styleSheets[0].cssRules[0].cssText)
    

    Additionally, the window can find an element's current style. For example, you can write:

    alert(window.getComputedStyle(square, "").backgroundColor)
    

    -- Rod Whiteley 02:19, 7 April 2006 (PDT)

     

    I got to this page in the process of trying to learn CSS and JavaScript.  The tutorial example did not work with either Firefox or Chrome.  From a different training book, realized that the script file was inserted at the beginning of the document and not the end.  Because of this, it did not have access to the document elements and failed to work.  Moving the script file to just above the </html> fixed this issue. I am still a novice, so I am hoping that someone else will come along and fix the example.  Since this is just an example of using JavaScript, it would also be easier on us novices to address both the button and the square in the same way. Why confuse us here?

    -- Griffin2003 4:09 EDT 21 Sept 2014

    Document Tags and Contributors

    Contributors to this page: Spark343, Rod Whiteley, Griffin2003
    Last updated by: Griffin2003,