-1

I wrote this code:

    <script>
function changeColor(newColor) {
 var currentLocation = window.location.href;

 if (window.location.pathname == "/communication-negotiation-and-conflict- management/")
       document.getElementById("color_var").style.backgroundColor = "lightblue";  

</script>

Course full:     <span style="color:white; display:inline-block;" id="color_var">63%       </span>

What I expect from the code is - function will change color of ID according the current url -so if the url is what I defineded (/communication-negotiation-and-conflict-management/) the ID (color_var) should change its background color.

I do not know why this is not working :-(

3 Answers3

0

I'm not sure if your code snippet is just incomplete, but it seems, that your function is missing the closing brackets.

Also, I can't see, where you're actually calling the function, maybe you should give a bit more context here!

Sender
  • 6,660
  • 12
  • 47
  • 66
jdepoix
  • 475
  • 1
  • 4
  • 11
0

Ah,

this is the first time I write to stackoverflow. So it might be a bit confusing. Let me explain it.

I created a widget in my Wordpress site and I am trying to make easy javascript function to create "Color changer" according the url.

So lets say - I have this page http://europeansummerschool.com/course/communication-negotiation-and-conflict-management/

And this course is "63%" full - so I want it to background-color those 63% with blue color.

I rewrite the code now like this:

<script>

var currentLocation = window.location.href;

if (currentLocation == "http://europeansummerschool.com/course/communication-negotiation-and-conflict-management/")
document.getElementById("color_var").style.backgroundColor = "lightblue";  

  </script>
Course full: <span style="color:white; display:inline-block;" id="color_var">63%</span>
0

Unfortunately I can't comment on this, due to lack of reputation, so I'll have to write another awnser..

You didn't really mention, if you're new code snippet is working or not, but I guess it isn't. The reason being, that your script tag is executed, before #color_var is added to the DOM. Therefore the element you're trying to retrieve by calling getElementById()isn't there yet.

Another source for errors could be, that you're comparing window.location.href to a String of the URL. If the URL varies just slightly, this won't work. For example if you're using https instead of http, or the url doesn't contain a trailing slash.

There a lot of different methods, to getting just the hostname and a lot of threads on SO. Take a look at this, for example.

jdepoix
  • 475
  • 1
  • 4
  • 11