Home > Net >  How to get access and change style of an element with JavaScript?
How to get access and change style of an element with JavaScript?

Time:09-21

I am coding a survey. If a button is clicked the color of the clicked button is changing. I want to provide the possibility to the user to deselect a button if he for example clicked or selected respectively the wrong button. Therefore, I changed the class of the selected button to have a exclusive access only to the selected button to set the style-attributes to default when deselect the button. I tried different ways but none of them worked. Where is my failure? My code is below.

window.onload = function() {
  const option = document.getElementsByClassName("button");

  const forward = document.getElementById("forward");

  Array.from(option).forEach(function(option) {
    option.addEventListener("click", () => {


      option.style.backgroundColor = "rgb(77, 55, 120)";
      option.style.opacity = "0.65";
      option.style.color = "white";

      //Changong buttons backgroundcolor to purple

      let keySelector = option.querySelector(".key-selector");
      keySelector.style.color = "white";
      //determine the key-selector and turn the color into white

      forward.style.color = "white";
      forward.style.backgroundColor = "rgb(77, 55, 120)";
      forward.style.transition = "1s ease";
      //changing the color of the continue-button to purple when at least one element is selected

      option.className = "selected-button";
      console.log(option.className);

      //replace class name of selected-element to provide the possibility to have access to the selected element in order to deselect if required
    });
  });
  const selectedButton = document.getElementsByClassName("selected-button");

  Array.from(selectedButton).forEach(function(selectedButton) {
    selectedButton.addEventListener("click", () => {
      //if selected element is clicked again turn the style-settings to default
      keySelector.style.color = "rgb(51, 51, 51)";
      keySelector.style.opacity = "0.6";

      selectedButton.style.backgroundColor = "rgb(226, 226, 226)";
      selectedButton.style.color = "black";
      selectedButton.style.opacity = "1";
      //return the colors when a button is deselected

      selectedButton.className = "button";
      console.log(option.className);
      //turn the class name to default to have provide the possibility to select the element again
    });
  });
};
body {
  font-family: 'Noto Sans Avestan', sans-serif;
}

.navbar {
  display: flex;
  list-style: none;
  background-color: rgb(77, 55, 120);
  margin: 0;
  position: fixed;
  width: 100%;
  gap: 4rem;
  height: 50px;
  text-align: center;
  line-height: 45px;
  left: 0;
  top: 0;
}

.nav-text {
  text-decoration: none;
  color: white;
  width: auto;
  cursor: pointer;
  font-size: 18px;
  padding-bottom: 5px;
}

.instruction {
  padding-top: 8rem;
  left: 10%;
  padding-bottom: 0px;
  width: auto;
  max-width: 730px;
  font-size: 20px;
  position: absolute;
}

.options {
  height: auto;
  max-height: 313px;
  max-width: 750px;
  width: auto;
  padding-top: 15rem;
  padding-bottom: 60px;
  display: flex;
  flex-direction: column;
  gap: 15px;
  position: sticky;
  left: 8rem;
}

.button,
.selected-button {
  background-color: rgb(226, 226, 226);
  height: 418.75%;
  width: auto;
  padding: 21px 25px 22px 25px;
  box-sizing: border-box;
  border-top-left-radius: 5px;
  border-top-right-radius: 5px;
  border-bottom-left-radius: 5px;
  border-bottom-right-radius: 5px;
  cursor: pointer;
  font-size: 18px;
  line-height: 16.8px;
  display: block;
  position: relative;
  top: 0px;
  bottom: 0px;
  right: 0px;
  left: 0px;
}

.text {
  margin-left: 4rem;
}

.button:hover {
  background-color: rgb(194, 194, 194);
  opacity: 0.8;
}

#backward:hover,
#forward:hover {
  background-color: rgb(77, 55, 120);
  color: white;
}

.key-selector {
  position: absolute;
  top: 50%;
  margin-top: -12px;
  font-size: 16px;
  line-height: 1.5em;
  text-align: center;
  width: 30px;
  display: block;
  opacity: 0.6;
  border: 1px solid;
  border-radius: 5px;
  border-top-left-radius: 5px;
  border-top-right-radius: 5px;
  border-bottom-left-radius: 5px;
  border-bottom-right-radius: 5px;
  height: 25px;
  color: rgb(51, 51, 51);
}

.button:hover .key-selector {
  color: black;
}

.button-bar {
  position: fixed;
  bottom: 0;
  width: 100%;
  display: flex;
  margin: 0;
  left: 0;
}

.nav-inner {
  cursor: pointer;
  width: 50%;
  text-align: center;
  line-height: 83px;
}

#backward {
  background-color: rgb(101, 93, 93);
  color: white;
}

#forward {
  background-color: rgb(191, 191, 191);
}
<div id="work-container">
  <ul >
    <li ><a  href="client.html">A</a></li>
    <li ><a  href="case.html" style=" border-bottom: 1px solid;">B</a></li>
  </ul>
  <div >
    <h3>Please choose an answer. You can choose more than one answers.</h3>
  </div>
  <div >
    <div >
      <div >
        <div >
          <span>A</span>
        </div>
        <div >1</div>
      </div>

    </div>

    <div >
      <div >
        <div >
          <span>B</span>
        </div>
        <div >2</div>
      </div>


    </div>

    <div >
      <div >
        <div >
          <span>C</span>
        </div>
        <div >3</div>
      </div>

    </div>

    <div >
      <div >
        <div >
          <span>D</span>
        </div>
        <div >4</div>
      </div>

    </div>

    <div >
      <div >
        <div >
          <span>E</span>
        </div>
        <div >5</div>
      </div>

    </div>
  </div>


  <div >
    <div  id="backward">
      < Back</div>
        <div  id="forward"> Continue ></div>
    </div>
  </div>

</div>

CodePudding user response:

You're only looping over selectedButtons when the page first loads. Since there are no elements with the class at that time, nothing gets the second event listener.

Instead of two different event listeners, use a single event listener that tests the class of the element.

if (option.classList.contains("selected-button")) {
    // do something
} else {
    // do somthing else
}

It's also generally better to use the classList methods than assigning to className, so you don't remove other, unrelated classes. This would allow you to add/remove the selected-button class without removing button, so you don't need to assign the same style to both classes in CSS.

CodePudding user response:

Let me tell you the mistakes in your code.

Array.from(option).forEach(function (option) {

is a very wrong way to add event listeners. Use event delegation.

option.className = "selected-button"; 

is a wrong way to add class. Use classlist.add()/classlist.remove().

const selectedButton = document.getElementsByClassName("selected-button");

You are adding a query of selected-button at the time of window load. You will not get any element in this case, because classname will be added if button is selected, and will not be present at the time of load. Event delegation will save you again.

element.style.backgroundColor = "purple"

This again is a piece of text from another world. Create a CSS class, .active and add/remove the CSS class.

CodePudding user response:

You literally need 0 javascript for this part. CSS has the :focus and :disabled pseudoclasses, and HTML has the "disabled" attribute and automatically sets the focused element for CSS (:focus is the selected button/input):

button {
  color: black;
  background: aqua;
  border: none;
  border-radius: 5px;
  padding: 4px 5px;
  transition-duration: 0.2s;
}

button:disabled {
  background: silver;
  color: gray;
}

button:focus {
  background: #aaf;
  outline: 2px solid aqua;
}
<button disabled>Disabled</button>
<button>Back</button>
<button>Next</butotn>

There's also the HTML form element, which can have required fields of different types:

<form>
  <input type="number" placeholder="Number"><br>
  <input type="password" placeholder="Password"><br>
  <input type="text" placeholder="Required text" required><br>
  <input type="date"><br>
  <input type="submit" value="Send"><br>
</form>

  • Related