user12038555
user12038555

Reputation:

document.getElementById changing color with variables

I'm using document.getElementById("banner").style.backgroundColor = COLOR to change something with cookies. I take the cookie and read it, and put the string into a variable (Ex: var backgroundcolor = "red") How would I put that into the COLOR slot as I don't know how to put a variable where COLOR is.

Heres my full code:

<script>
            function getCookie(cname) {
  var name = cname + "=";
  var ca = document.cookie.split(';');
  for(var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}
function checkCookie() {
  var bannerlinkcolor = getCookie("bannertheme");
  if (bannerlinkcolor = 0) {
      var textcolor = "#000000";
      var bgcolor = "#ff0000";
  } else {
    var textcolor = "#FFFFFF";
      var bgcolor = "#800080";

  }
}
        </script>
        <script>
document.getElementById("banner").style.color = textcolor;
            document.getElementById("banner").style.backgroundColor = bgcolor;
</script>
    </head>
    <body>
            <div id="banner" style="border:2px dotted orange; height:20px; width:100%; "><center>Check out our <a href="https://www.youtube.com/channel/UC4Eg3V26uXxWY-M639mGDrQ" target="_blank">Youtube</a> Channel! &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Help reinstate Net Neutrality! Visit <a href="https://www.battleforthenet.com/" target="_blank">https://www.battleforthenet.com/</a>!!<center></div>
        </body>    
</html>

(I left out the top because that had some Google Analytics stuff)

Heres where I store the cookie data:

function switchTheme(e) {
    if (e.target.checked) {
    var r = confirm("Are you sure you want to switch on light mode? (It hurts my eyes)");
    if(r == true) {
        document.documentElement.setAttribute('data-theme', 'light');
        localStorage.setItem('theme', 'light'); //add this
        setCookie("bannertheme", 1, 1);
        }else {
        toggleSwitch.checked = false;
        }
    }
    else {
        document.documentElement.setAttribute('data-theme', 'dark');
        localStorage.setItem('theme', 'dark'); //add this
        setCookie("bannertheme", 0, 1);
    }    
}

The toggling thing is activated by a switch

I've tried these two things and neither works:

document.getElementById("banner").style.backgroundColor = var(bgcolor);

document.getElementById("banner").style.backgroundColor = bgcolor;

document.getElementById("banner").style.backgroundColor = VARIABLE_HERE;

I need it to change the color of banner to purple

Upvotes: 0

Views: 2926

Answers (3)

Pushprajsinh Chudasama
Pushprajsinh Chudasama

Reputation: 7949

You can simply do it using the following snippet .

var purple = //get cookie code 
document.getElementById("banner").style.backgroundColor = purple;

UDATED
Don't use the two different scripts to tag include all the thing in single script .
Check out my code

<!DOCTYPE html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

</head>
<body >

    <div id="banner" style="border:2px dotted orange; height:20px; width:100%; "><center>Check out our <a href="https://www.youtube.com/channel/UC4Eg3V26uXxWY-M639mGDrQ" target="_blank">Youtube</a> Channel! &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Help reinstate Net Neutrality! Visit <a href="https://www.battleforthenet.com/" target="_blank">https://www.battleforthenet.com/</a>!!<center></div>

    </body>
    </html>

</body>
</html>

<script>
    function getCookie(cname) {
        var name = cname + "=";
        var ca = document.cookie.split(';');
        for(var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') {
                c = c.substring(1);
            }
            if (c.indexOf(name) == 0) {
                return c.substring(name.length, c.length);
            }
        }
        return "";
    }
    function checkCookie() {
        var textcolor = "";
        var bgcolor = "";
        var bannerlinkcolor = getCookie("bannertheme");
        if (bannerlinkcolor == 0) {
             textcolor = "#000000";
             bgcolor = "#ff0000";
        } else {
             textcolor = "#FFFFFF";
             bgcolor = "#800080";

        }
        document.getElementById("banner").style.color = textcolor;
        document.getElementById("banner").style.backgroundColor = bgcolor;

    }
</script>

Upvotes: 2

Syed
Syed

Reputation: 704

Well it seems pretty easy one you done it, right as all trivial realities of life. So here is the walk through.

  • In JS LHS = RHS,
  • LHS is object reference and RHS is value assigned to that reference.
  • RHS can be string or reference to another object which has value.

EXAMPLE

var abc = 123;

var def = abc;

There is no rule saying how this cannot be applied to your scenario;

var colorcode = "#000000";
var colorname = "black";

document.getElementById("banner").style.backgroundColor = colorcode; 
document.getElementById("banner").style.backgroundColor = colorname; 

So our intention is to make the LHS = RHS equation fit the bill.

Suppose we we have cookie created in all its manifestation.

document.cookie = "colorcode=#000000";

or

document.cookie = "colorcode=black";

That is the easy part but when it comes to retrieving the cookie by name you have to run a mile or two before you can reach the point.

First get collection of all the cookies

var allcookies = document.cookie;

This comes in a string like fashion as in below example;

__utmc=264131991; __utma=264131991.1393864252.1562868442.1567905512.1567968949.26; __utmz=264131991.1567968949.26.13.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided); __utmb=264131991.1.10.1567968949; colorcode=#000000;

We have to convert it into array by split function as following;

var cookiearray = allcookies.split(';');

Now we can travel around the array via for loop (its much faster) and retrieve our value;

for(var i=0; i<cookiearray.length; i++) {
                  name = cookiearray[i].split('=')[0];
                  value = cookiearray[i].split('=')[1];
                  if (name = "colorcode") {
                  var colorvalue = value; 
                  }

               }

Created colorvalue which captures the value if name matches.

Now we can use LHS = RHS to set value for background colour.

document.getElementById("banner").style.backgroundColor = colorvalue;

there is no hindrance to place above code directly into for loop inside if condition.

How ever it is not reusable. Thus we have to resort to function as exemplified by W3 Schools.

function getCookie(cname) {
  var name = cname + "=";
  var ca = document.cookie.split(';');
  for(var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}
document.getElementById("banner").style.backgroundColor = getCookie("colorcode");

Function takes the argument, creates local variable inside function, then collects and splits the cookie collection into array.

It then runs a loop with nested while until condition meets as the first character of each array value, which is white space.

In side while loop, it creates a new variable by substring() method extracting all characters from string other than 1st character, which in our case is white space.

once done in while loop in next step of parent for loop it runs indexof method as truthy.

If true return value again using sub-string value.

Is this the most elegant method probably not, but either which way you will have to run above number of steps before getting value from cookie.

If you have provision why not run the same through local storage.

localStorage.setItem("colorcode", "#000000");

 document.getElementById("banner").style.backgroundColor = localStorage.getItem("colorcode");

Saves you bit of headache.

Upvotes: 0

tom
tom

Reputation: 10559

To store styling data it is better to use sessionStorage instead of cookies.

sessionStorage.setItem('myBackgroundColor', 'red');

var backgroundColor = sessionStorage.getItem('myBackgroundColor');

document.getElementById("banner").style.backgroundColor = backgroundColor;

Upvotes: 0

Related Questions