Your function has an error in if
: the comparison operator would be two ==
signs and not just one ( =
). In JavaScript you'll 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 redefining the value of online
to 1
, it means that it will always be 1
in if
following.
Even so, you must also 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 set the initial color of the link in CSS as well as the spacing of the circle to the text using a margin-right
, so you do not need to put a space character between the circle and the text. p>
To change the text, you can use the nextSibling.textContent
methods. The nextSibling
will select the next node after the circle (in this case, the text). And textContent
will change the text.
To change the color of the link (logo, circle, and text together), you can use the .parentNode
method. As in the function the selector used is the circle, the .parentNode
will select the <a>
tag that is the parent.
With these fixes, your code could look like this:
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>