Its function has an error in the if
: the comparison operator would be two signals ==
and not just one (=
). In Javascript you compare if one value is equal to another with two ==
- in some cases up to three: ===
(see here the operators used in various cases).
Another problem is that within the function you are resetting the value of online
for 1
, That means he’ll always be 1
in the if
next.
Even so, you also need to change the value of the variable online
when one of the conditions is met (if...else
). At no time is this done, so the value of the variable is always the same.
My suggestion is that you define in CSS the initial color of the link, as well as the spacing of the circle to the text, using a margin-right
, so you don’t need to put a space character between the circle and the text.
To change the text, you can use the methods nextSibling.textContent
. The nextSibling
will select the next node after the circle (in this case, the text). And the textContent
will change the text.
To change the color of the link (logo, circle and text together), you can use the method .parentNode
. As in the function the selector used is the circle, the .parentNode
will select the tag <a>
who is the father.
With these fixes, your code could be this way:
var online = 1;
function myFunction(){
var onOff = document.getElementById("foo");
if(online == 1){
online = 0;
onOff.parentNode.style.color = "darkred";
onOff.nextSibling.textContent = "Offline";
}else{
online = 1;
onOff.parentNode.style.color = "darkgreen";
onOff.nextSibling.textContent = "Online";
}
}
/* seleciona a tag <a> onde o atributo onclick começa com myFunction*/
a[onclick^='myFunction']{
color: darkgreen;
}
#foo{
margin-right: 5px;
}
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.13/css/all.css" integrity="sha384-DNOHZ68U8hZfKXOrtjWvjxusGo9WQnrNx2sqG0tfsghAvtVlRW3tvkXWZh58N9jp" crossorigin="anonymous">
<a href="#" onclick="myFunction()">
<i class="fa fa-circle text-success" id="foo"></i>Online
</a>
If any answer solved your problem mark it as accepted. See how in https://i.stack.Imgur.com/evLUR.png and why in https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta/1079#1079
– user60252