Search code examples
javascripthtmlvariablesweb-componentaframe

How do I access JavaScript variable under Color portion of HTML code?


I would like to access the variable "theSkyColour" inside the HTML code below as shown. May I know how do I access it as shown?

The following is the code I have written:

function getSkyColour() {
  var theSkyColour = localStorage.getItem('skySet[enter image description here][1]ting');
}
<a-sky id="skyColor" src="#sky" 
material="shader:gradient; topColor: <<I want to access theSkyColor here>>; bottomColor: <<I want to access theSkyColor here>> ; offset:0;"></a-sky>

I have viewed other answers like the one here: Javascript variable access in HTML, however, it did not work for me as I am unable to change the color of the sky in the viewing page.

I've created the following HTML pages. 1. A settings page to adjust the color of the sky saved in a localStorage as "skyColor". 2. A viewing page for the user to view the color of the sky.

The reason why I have an a-sky tag is that I am using aframe.io

Update: After attempting to use JavaScript along with localStorage Sessions:

Javascript Code:

<script>
function getSkyColor() {
  var theSkyColor = localStorage.getItem('skySetting');
}
getSkyColour()

var myAttr = "shader:gradient; topColor:"+theSkyColor+"; 
bottomColor:"+theSkyColor+"; offset:0;"
document.getElementById(‘skyColor’).setAttribute(“material”,myAttr)
</script>

HTML Code:

  <a-sky id="skyColor" src="#sky" material="shader:gradient; offset:0;"></a-sky>

Unfortunately, it still does not work, as the display I get is not what I have expected, which is a night sky under the RGB color: 41 35 71. (See attached screenshot)

Failed display of desired colors RGB 41 35 71

What I want and What I have


Solution

  • Unless you are using a framework like Angular or django, it is not possible to access variables in your HTML code, instead you can construct the attribute in your Javascript and add it to the element.

    EX:

    var myAttr = "shader:gradient; topColor:"+skyColor+"; bottomColor:"+skyColor+"; offset:0;"
    $("#skyColor").attr("material",myAttr)
    

    Update: without using jQuery:

    <script>
    function getSkyColour() {
      var theSkyColour = localStorage.getItem('skySetting');
    }
    getSkyColour()
    
    var myAttr = "shader:gradient; topColor:"+theSkyColour+"; bottomColor:"+theSkyColour+"; offset:0;"
    document.getElementById(‘skyColor’).setAttribute(“material”,myAttr)
    
    </script>