how to change btn background when click /HTML

I made a button like read more and when I press it, a text opens downwards. When the text opens, the background of the button will change and when I press the button again to close the text (such as read less), the background of the button will return to its original state.How to do that

function myFunction() {
        var dots = document.getElementById("dots");
        var moreText = document.getElementById("more");
        var btnText = document.getElementsByClassName("skillBtn");
      
        if (dots.style.display === "none") {
          dots.style.display = "inline";
          btnText.innerHTML = "Read more";
          moreText.style.display = "none";
        } else {
          dots.style.display = "none";
          btnText.innerHTML = "Read less";
          moreText.style.display = "inline";
        }
      }
#more {display: none;}
<div align="center"><h1 id="skillsid" style="margin-top:10px ;"> Codding dilleri <span id="dots"></span> </h1><span id="more">
    something is written here
    
    <div align="center"><a href="#skillsid"><button class="skillBtn" onclick="myFunction()" ></button></a></div>

>Solution :

What you’re trying to do is called accordion. There is no reason to write this with JS as HTML has <details> and <summary> for that:

#more {
  display: none;
}
<details>
  <summary>Codding dilleri</summary>
  something is written here
</details>

IF you want to change styles on a button click then you should toggle CSS-classes as below:

let button = document.querySelector('button');

button.addEventListener('click', function() {
  let more = document.querySelector('.more');
  more.classList.toggle('d-block');
  button.classList.toggle('bg-red');
  button.textContent = (button.textContent === 'Read More') ? 'Read Less' : 'Read More';
})
.more { 
  display: none; 
}

.d-block {
  display: block;
}

.bg-red {
  background-color: red;
}
<div align="center">
  <h1 id="skillsid" style="margin-top:10px ;">Codding  dilleri</h1>
  <div class="more">
    something is written here
  </div>
  <button class="skillBtn">Read More</button>
</div>

Leave a Reply