Home > Blockchain >  change img after click
change img after click

Time:11-11

Hi i doing a mini project of my class. I make the website book ticket for movies. I want to change color of the seat after click. But it just work for first seat. I want it work for other seat. Thank you.

const img=document.getElementById('seat')
let toggle = true;
img.addEventListener('click',function(){
  toggle=!toggle;
  if(toggle){
    img.src = 'seat.png';
  }
  else{
    img.src = 'seat2.png';
  }
  
})

enter image description here

CodePudding user response:

You will need to do this for every seat, not just the one seat. You could do this by calling a function when the seat is clicked.

function selectSeat(element) {
   element.classList.toggle('active');
   if (!element.classList.contains('active')) {
     element.src = 'seat.png';
   } else {
     element.src = 'seat2.png';
   }
}

This function uses a class called 'active' to tell if the seat was clicked not variables.

You can then call this function using the onclick attribute and passing the element as a parameter.

<img onclick='selectSeat(this)'>

CodePudding user response:

If you want to use getElementById, then each seat would need a different Id. If they all have the Id 'seat', then it will probably just grab the first one, which is the behaviour you are currently seeing.

You need a better way to select the individual seat element based on where the user clicks. It may be possible to build the behavior directly into the seat element. Hard to tell with the amount of code given, would need to see more.

  • Related