Javascript, change colour of element on-click with if-statement

Viewed 2202

I have no idea how to change the colour of my element if the colour's crimson to white. It has me confused because I've tried many solutions such as turning them into variables. Would anyone be able to tell me what I'm doing wrong, or possibly point me in the right direction? I've tried "duplicate" questions, but none of them really share the same issue.

<button class="btn-startcall10" onclick="recorda()"><i class="fa fa-wave-square"></i> </button>

  function recorda() {
    document.getElementsByClassName("fa-wave-square")[0].style.color = "crimson";
      if () {}
  }
3 Answers

You can use Element.style.color in the javascript to get the current color of the element.

Then based on that color you can change the color of your element.

let clickElement = document.getElementById("span-to-change-color");

clickElement.addEventListener("click", changeColor);

function changeColor() {

  if (clickElement.style.color == "red") {
    clickElement.style.color = "blue";
  } else {
    clickElement.style.color = "red";
  }
}
<span style="color: red;" id="span-to-change-color">I am red(Click Me)</span>

you can try something like this

 function changeColor(){
    el = document.getElementById("fa-wave-square");
  if(el.style.color === 'crimson'){
    el.style.color = 'white';
  } else {
    el.style.color = 'crimson';
  }
 }

https://jsfiddle.net/Lyuvf9a6/3/

First of all you have to add an event listener for on click event e.g

YOUR_ELEMENT.addEventListener("click", YOUR_LISTENER) // e.g recorda

Your event listener will get the event object from where you can access the object but if it's a nested object e.g your event listener is on div but you have a span inside and on click of span on click event will be triggered and the target object will be the span. But you can cache YOUR_ELEMENT and use that also.

Now you can check the style color for the color and do as necessary.

if (YOUR_ELEMENT.style.color === 'crimson') {
  YOUR_ELEMENT.style.color = 'white'
} else {
  YOUR_ELEMENT.style.color = 'crimson'
}

Here is a sample code e.g

<div id="textChange">Some text</div>
<script>
  var elem = document.getElementsById('textChange')
  function changeColor(e) {
    // You can use and get elem using
    // var ele = e.target
    // Or as we have cached elem we can use that

    if (elem.style.color === 'red') {
      elem.style.color = 'green'
    } else {
      elem.style.color = 'red'
    }
  }

  elem.addEventListener('click', changeColor)
</script>
Related