简体   繁体   中英

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

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 () {}
  }

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 eg

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 eg 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 eg

<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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM