Home > Software engineering >  How to hide only clicked button belonging to same class of buttons using Vanilla JS HTML CSS
How to hide only clicked button belonging to same class of buttons using Vanilla JS HTML CSS

Time:06-04

I am stuck with situation where I am rendering a data.json into HTML using JS. Everything is working fine. Json data is rendered into html using loop which results in multiple objects having same class.

Because of this every button I created belongs to same class in loop. Now the question; I want to hide only specific button that is clicked and not all the buttons of the class.

var X = document.getElementsByClassName("buttons");
function HideClickedButton() {

  for (let x of X) {
    if (x.style.display === "none") {
      x.style.display = "block";
    
    } else {
      x.style.display = "none";
    }
  }
}

for (const button of X) {
    button.addEventListener('click', HideClickedButton);
}
<button >Test</button>
<button >Test</button>
<button >Test</button>
<button >Test</button>

the above code is hiding all the buttons of the same class.

and if use only document.querySelector(".buttons").style.display = "none"

Then it is always hiding the first button no matter which button is pressed.

Edited Part:

 <div onclick="addToCart(${product.price})">
    <button  onclick="hideAddButton(this)" type="button">ADD</button>
  </div>
  <div onclick="addToCartRemove(${product.price})">
    <button  onclick="showRemoveButton(this)" type="button">Remove</button>
  </div>

So. my code is something like this in JS which is basically rendering list from JSON. After rendering, totals buttons are 12. In a group of 6 (see image). Now, I don't want to show remove button initially. It will only show when corresponding ADD button is clicked. When ADD button is clicked it will hide and Remove button will takes it place while other ADD buttons remains the same. Please let me know if you understand.enter image description here

CodePudding user response:

Either attach a listener to each button and hide the element that was clicked on...

const buttons = document.querySelectorAll('.button');

buttons.forEach(button => {
  addEventListener('click', handleClick)
});

function handleClick(e) {
  e.target.classList.add('hide');
}
.hide { display: none; }
<button >one</button>
<button >two</button>
<button >three</button>
<button >four</button>
<button >five</button>

...or wrap your buttons in a container, use event delegation and only attach one listener to that container (this will capture all the events from its child elements as they "bubble up" the DOM). Check the clicked element has class .button, and then hide it.

const buttons = document.querySelector('.buttons');

buttons.addEventListener('click', handleClick);

function handleClick(e) {
  if (e.target.matches('.button')) {
    e.target.classList.add('hide');
  }
}
.hide { display: none; }
<div >
  <button >one</button>
  <button >two</button>
  <button >three</button>
  <button >four</button>
  <button >five</button>
</div>

CodePudding user response:

You can add an event listener for the click of your button.

var X = document.getElementsByClassName("buttons");
    X.forEach(function (element) {
        element.addEventListener("click", function () {
            this.style.display = "none";
        })
    })

CodePudding user response:

  1. document.querySelector() is only going to select the first element than matches the selector. You need document.querySelectorAll() to get all elements that match.
  2. But you can do this much easier by attaching to the event handler's for all your buttons once they are rendered.

You sort of imply that the button that is clicked should disappear, and the other buttons should reappear. If this is not the case you can comment out the line of code below that change the style of "other" buttons to block.

Edit: e.PreventDefault() and e.StopPropagation() are there to prevent standard button click behavior (submitting forms and whatnot.) If you do not want to suppress this behavior, you can simply remove these lines.

const buttons = document.getElementsByClassName('buttons');

[...buttons].forEach( (button) => {
   button.addEventListener( 
      'click', 
      (e) => HideClickedButton( e, button ), 
      false 
   );
});

function HideClickedButton( e, button ) {
  [...buttons].forEach( (other) => other.style.display = 'block' );
  e.preventDefault();
  e.stopPropagation();
  button.style.display = 'none';
}
<div>
  <button >Button 1</button>
  <button >Button 2</button>
  <button >Button 3</button>
  <button >Button 4</button>
</div>

CodePudding user response:

You can do this using onclick="yourfunction(this)" , please see snippet below.

Other solution is to use an event listener.

function HideClickedButton(x) {
      x.style.display = "none";
}
<div>
  <button onclick="HideClickedButton(this)" >Button 1</button>
  <button onclick="HideClickedButton(this)" >Button 2</button>
  <button onclick="HideClickedButton(this)" >Button 3</button>
  <button onclick="HideClickedButton(this)" >Button 4</button>
</div>

EDIT : Following your question in the comments, here is how to toggle display of button 1 when clicking button 8, and vice versa. It does not matter which class are the buttons because it is the onclick attribute that triggers the function, not their class.

function HideClickedButton(x) {
      var parent = x.parentNode;
      var index = [].indexOf.call(parent.children, x);
      //if clicked element is index 0 in parent element's children (button 1)
      if(index==0){
        //show element index 7 (button 8)
        parent.children[7].style.display = "inline-block"; 
      }
      //else if clicked element is index 7 in parent element's children (button 8)
      else if(index==7){
        //hide or show element index 0 (button 1)
        parent.children[0].style.display = "inline-block"; 
      }
      //we hide clicked button
        x.style.display = "none";
}
<div>
  <button onclick="HideClickedButton(this)" >Button 1</button>
  <button onclick="HideClickedButton(this)" >Button 2</button>
  <button onclick="HideClickedButton(this)" >Button 3</button>
  <button onclick="HideClickedButton(this)" >Button 4</button>
  <button onclick="HideClickedButton(this)" >Button 5</button>
  <button onclick="HideClickedButton(this)" >Button 6</button>
  <button onclick="HideClickedButton(this)" >Button 7</button>
  <button onclick="HideClickedButton(this)" >Button 8</button>
</div>

  • Related