Home > Mobile >  How activate or deactivate a button from a list of buttons
How activate or deactivate a button from a list of buttons

Time:10-25

I have a list of buttons inside a div that emulates a project preview in a dashboard. I want to let the user select the project so it can be opened or erased.

So I need a function (that for sure exists but I don't know it) to identify the list of buttons inside the div, and when the user clicks on one button, activate it and simultaneously deactivate the other buttons

I'm identifying the buttons like:

var container = document.querySelector('#buttonscontainer');
var matches = container.querySelectorAll('div.divscontainer > button');
//identify the buttons inside the div, maybe not necessary...
  for (var i = 0; i < matches.length; i  ) {
    //activate the current button
    //deactivate other buttons (if ever been activated) 
  }

May be with an addEventListener inside the div, but I don't know where to begin.

I don't want an exact answer of course, just a tip to know with which functions can I start exploring.

Hope it's clear enough,

Thanks everyone! :)

CodePudding user response:

This does what you want:

<div id="buttonscontainer">
  <button  id="btn1">action 1</button>
  <button  id="btn2">action 2</button>
  <button  id="btn3">action 3</button>
  <button  id="btn4">action 4</button>
</div>

<style>
  .btn {
    animation: btn 1s infinite;
  }

  @keyframes btn {
    50% {
      outline: 3px solid blue;
    }
  }

  .btn--selected {
    outline: 3px solid yellow !important;
  }
</style>

<script>
  const buttonscontainer = document.getElementById('buttonscontainer')
  buttonscontainer.addEventListener('click', event => {
    const target = event.target
    if (target.className !== 'btn') return

    Array.from(buttonscontainer.children).forEach(child => child.classList.remove('btn--selected'))
    target.classList.add('btn--selected')
  })

</script>

We give an animation to the buttons so that the user knows that they are selectable, in this case we put a blue outline. infinite means that it always does the animation. Also, we listen with an event when there's a click on any button in order to put it a class with a yellow outline in it.

If anyone has any questions about this code, let me know and I'll be happy to explain it.

  • Related